【发布时间】:2020-05-13 07:28:55
【问题描述】:
我正在尝试从具有多个关键字的四个不同文本文件中提取信息。我想提取这些关键字并将词频附加到关键字上。文本文件如下所示:
test1 = apple banana lemon
test2 = apple banana
test3 = lemon apple lemon
test4 = apple lemon grape
我认为粗体代码(第二段)有问题,我不确定应该如何构造初始字典。
test1= [line.rstrip('\n') for line in open("test1.txt")]
test2= [line.rstrip('\n') for line in open("test2.txt")]
test3= [line.rstrip('\n') for line in open("test3.txt")]
test4= [line.rstrip('\n') for line in open("test4.txt")]
**
text_file = test1, test2, test3, test4
word_frequencies = 0
text_collection = {}
**
def dictionary(text):
keywords = re.split(r'\W', text)
print(text)
word_frequencies = dict()
for word in keyword:
if word in word_frequences:
word_frequences[word] += 1
else:
word_frequencies[word] = 1
return word_frequencies
for all in text_file:
file = open(all)
text = file.read()
print(file)
text_collection[all] = dictionary(text)
print(text_collection)
期望的输出:
{'test1.txt': {'apple': 1, 'banana': 1, 'lemon': 1},
'test2.txt': {'apple': 1, 'banana': 1},
'test3.txt': {'apple': 1, 'lemon': 2},
'test4.txt': {'apple': 1, 'lemon': 1, 'grape': 1}}
我宁愿不使用导入的库作为答案。这段代码更多的是为了练习而不是效率:)
【问题讨论】:
-
开始将
text_file变成一个有效的Python 构造:一个list。word_frequencies(在其所有变体拼写中)是函数dictionary的本地函数,因此它不需要在其外部进行初始化。 -
这能回答你的问题吗? Efficiently count word frequencies in python
-
它很有用,但我宁愿不使用导入的库作为答案。这段代码更多的是为了练习而不是效率:)。不过,谢谢!
标签: python python-3.x dictionary