Python if列表中的元素存在于文件追加中,成功率为%



因此,我的目标是浏览文件夹中的许多文件,搜索列表中包含的某些字符串值,然后在本地列表中附加包含这些字符串的文件,以及这些字符串值在所述文件中的值我的问题似乎是";任何";函数不适用于";键";?有没有其他我应该使用的功能或解决方法?

类似这样的东西:

import os
success = []
keywords = ["the", "of", "from", "north", "south", "east", "west", "to", "county", "have", "one", "two", "three", "four", "five", "six","seven", "eight", "nine"]
total = len(keywords)
folder = ("C:Folder//Path")
folder_paths = [os.path.join(folder, file) for file in os.listdir(folder)]
for f in folder_paths:
    wins= 0
    for key in keywords in f:
        wins+=1
    confidence = Str(wins/total) + "%"
    if confidence>=1:
        success.append(str(f) + confidence)
print(success)

这里是一个带有修复程序的重构。

filter(lambda key: key in f, keywords)返回在f中找到的keywords的列表,其len指示有多少。

这可能会被重新表述为使用all()(而不是any(),一旦找到一个匹配就终止(,但这似乎是一种复杂的做法。

这仍然假设您正在查找文件名称中的字符串,而不是正在循环的文件的内容。

其他变化:

  • total太琐碎了,我只是内联了它;Python优化器可能只为我们计算一次
  • folder_paths只使用过一次,因此将其内联
  • 前向斜线不必加倍。您似乎在C:之后缺少斜杠,所以添加了它
  • f已经是一个字符串,因此str(f)是多余的
  • Str()显然应该是str()
  • confidence必须是一个数字,以便比较它是否大于1
import os
success = []
keywords = ["the", "of", "from", "north", "south", "east", "west", "to", "county", "have", "one", "two", "three", "four", "five", "six","seven", "eight", "nine"]
folder = ("C:/Folder/Path")
for f in [os.path.join(folder, file) for file in os.listdir(folder)]:
    wins = len(list(filter(lambda key: key in f, keywords)))
    confidence = wins/len(keywords)
    if confidence >= 1:
        success.append(f + str(confidence) + "%")
print(success)

一个更好的设计可能是创建一个返回f: wins/len(keywords)字典的函数,并将调用方格式转换为人类可读的形式进行打印。

您可以尝试使用nltk,这些都是经过验证的库。以下是可以帮助您的代码。

# import nltk and pandas
import nltk
import pandas as pd
my_files=['my_random.txt','my_random.txt'] # my files
my_keyword=['solutions','Solar']
df_list=[] # for storing dataframe of each file
for each_file in my_files:
    with open(each_file,"r") as f_r:
        file_content=f_r.read()
    
    tokens = nltk.tokenize.word_tokenize(file_content)
    valid_tokens=[each_t for each_t in tokens if each_t in my_keyword] # words which are in keyword
    fd = nltk.FreqDist(valid_tokens) # dict word:frequency
    df = pd.DataFrame.from_dict(fd, orient='index')
    df_list.append(df) # now df_list will have all word frequencies

在df_list中,列表包含每个文件的数据帧。如果需要,您可以将它们移动到结果。

result=df_list[0]
for each_df in df_list[1:]:
    result=result+each_df

结果

最新更新