【发布时间】:2023-03-04 02:25:02
【问题描述】:
from collections import Counter
input = 'file.txt'
CounterWords = {}
words = {}
with open(input,'r', encoding='utf-8-sig') as fh:
for line in fh:
word_list = line.replace(',','').replace('\'','').replace('.','').lower().split()
for word in word_list:
if len(word) < 6
continue
elif word not in CounterWords:
CounterWords[word] = 1
else:
CounterWords[word] = CounterWords[word] + 1
N = 50
top_words = Counter(CounterWords).most_common(N)
for word, frequency in top_words:
print("%s %d" % (word, frequency))
目前,我可以选择两个最常用的单词,其中字符串超过 X 个字符。
程序应筛选文本并计算以下单词:
“气候金融” “市场营销失败” “巴黎 2015”
仍应包含每个字符串的最少字符数,以防止出现“I and”等结果。
【问题讨论】:
-
获取
word_list[i:i+1]并使用它。 -
也许你应该首先删除所有短词——所谓的“停用词”。您可以使用模块 NLTK 中的停用词。见:Stopword removal with NLTK
-
"get word_list[i:i+1]" 看起来很简单。我必须把它放在哪里?在循环内还是在开头?
-
创建新的for循环
for i in range(len(word_list)-1): word_list[i:i+1] -
我愿意:
for word in range(len(word_list)-1): word_list[word:word+1](而不是上面原始代码中的for word in word_list:(第 9 行)我在下一行出现错误if len(word) < 6:-> TypeError: object of type 'int' 没有 len()