问题描述
我正在尝试在python中创建一个单词计数器,该计数器打印最长的单词,然后按频率对5个字母以上的所有单词进行排序。最长的单词有效,而计数器有效,我只是想不出如何使它仅检查5个以上的字母。如果我运行它,它可以工作,但是5个字母以下的单词仍然存在。
这是我拥有的代码:
print(max(declarationWords,key=len))
for word in declarationWords:
if len(word) >= 5:
declarationWords.remove(word)
print(Counter(declarationWords).most_common())
解决方法
您可以创建一个新列表,其中将包含带有您的条件(过滤器)的单词并使用它:
>>> s = ["abcdf","asdfasdf","asdfasdfasdf","abc"]
>>> new_s = [x for x in s if len(x) >= 5]
>>> new_s
['abcdf','asdfasdf','asdfasdfasdf']
>>>
或其他方法
>>> new_s = filter(lambda x: len(x) >= 5,s)
>>> Counter(new_s)
Counter({'abcdf': 1,'asdfasdf': 1,'asdfasdfasdf': 1})
,
我发现您可以找到对您的代码有用的更改:D
Longest_words=[]
print(max(declarationWords,key=len))
for word in declarationWords:
if len(word) >= 5:
Longest_words.append(word)
print(Counter(Longest_words).most_common())