所以我写了一些代码来确定文本文件中最常见的 4 个单词,然后找到所有出现 2% 或更多的单词。到目前为止,我的代码运行良好。但是我必须将 for 循环转换为列表推导。
到目前为止,我已经尝试过:
percent_list = [word, freq in word_counts.most_common(total) if ((freq/total)*100) >= 2.0]
对于第二个 for 循环,(请参阅下面的完整代码。但它不起作用。对于列表理解来说,这似乎有点长,因为所有在线内容似乎都短得多。
这是整个程序。总共有两个 for 循环。
from collections import Counter
from operator import itemgetter
STOP = ["the", "and", "in", "to", "a", "of", "at", "it", "but", "its","it's", "that", "was", "with", "as", "are", "i","this", "for", "if"]
word_counts = Counter()
with open("file.txt") as f:
for token in f.read().split():
if token.lower() not in STOP:
word_counts[token.lower()] += 1
print( word_counts.most_common(4), ":")
total = sum(word_counts.values())
print("nWords that occur for 2% or more are: ")
for word, freq in word_counts.most_common(total):
if ((freq/total)*100) >= 2.0:
print("n {} ".format(word))
这应该可以解决您的问题。它将返回单词和频率的元组列表。
percent_list = [(word, freq) for word,freq in word_counts.most_common(total) if ((freq/total)*100) >= 2.0]
通过大多数简单的理解,我们可以首先看看它们展开时的样子。
一般来说,对这种形式的list
理解:
result = []
for element in source:
if predicate(element):
result.append(modify(element))
可以减少到:
result = [modify(element) for element in source if predicate(element)]
这里的问题是我们一次迭代两个元素,因为等效的source
是 word_counts(most_common).total
.
因此,我们可以这样编写展开的for
循环:
result = []
for word, freq in word_counts.most_common(total):
if ((freq / total) * 100) >= 2:
result.append((word, freq))
注意word, freq
周围有一对额外的括号,它形成了一个tuple
,这是一个元素。请记住,您一次只能将一个元素添加到list
到 append
。
这给了我们以下理解:
[(word, freq)
for word, freq in word_counts.most_common(total)
if ((freq / total) * 100) >= 2]