我有一个docs.txt文件,其中包含以下三行:
joyously urgently truthfully seemingly broadly urgently knowingly urgently steadily
joyously urgently truthfully seemingly rigidly broadly rigidly suddenly healthily commonly often
tremendously totally steadily sharply totally
我有一个querys.txt文件,其中包含:
urgently
rigidly suddenly
totally steadily
以及守则:
dictionary = {}
angledictionary={}
document= open('docs.txt', 'r')
for line in document:
lined=line.split()
for word in lined:
if word not in dictionary.keys():
dictionary[word]=0
dictionary[word]+=1
dictionary=dict.fromkeys(dictionary,0)
with open("queries.txt", "r") as open_queries:
searchquery = open_queries.read().split("\n")
with open('docs.txt', 'r') as openrelevancy:
words = openrelevancy.read().split("\n")
for query in searchquery:
print('Query:', query)
relevant = []
line_number = 0
for word in words:
line_number += 1
if query in word:
relevant.append(line_number)
print('Relevant Documents:', *relevant)
现在,每行的字典字数为0,我正在尝试这样做: 对于第1行:
{'joyously': 1, 'urgently': 3, 'truthfully': 1, 'seemingly': 1, 'broadly': 1, 'knowingly': 1, 'steadily': 1, 'rigidly': 0, 'suddenly': 0, 'healthily': 0, 'commonly': 0, 'often': 0, 'tremendously': 0, 'totally': 0, 'sharply': 0}
第2行:
{'joyously': 1, 'urgently': 1, 'truthfully': 1, 'seemingly': 1, 'broadly': 1, 'knowingly': 1, 'steadily': 1, 'rigidly': 2, 'suddenly': 1, 'healthily': 1, 'commonly': 1, 'often': 1, 'tremendously': 0, 'totally': 0, 'sharply': 0}
第3行:
{'joyously': 0, 'urgently': 0, 'truthfully': 0, 'seemingly': 0, 'broadly': 0, 'knowingly': 0, 'steadily': 0, 'rigidly': 0, 'suddenly': 0, 'healthily': 0, 'commonly': 0, 'often': 0, 'tremendously': 1, 'totally': 2, 'sharply': 1}
我怎样才能解决这个问题
下面的代码将计算给定文件中的每个单词
一个简单的方法是使用
collections.Counter
:结果:
或者你可以用口述:
结果:
相关问题 更多 >
编程相关推荐