如何使用python创建一个函数来查找少于4个字符的单词的频率?
定义一个函数short_words(line),该函数接受单词列表类型的参数行,并返回一个单词频率小于4的字典。键是3个或更少字符的单词,值是这些单词的频率。如何使用python创建一个函数来查找少于4个字符的单词的频率?,python,Python,定义一个函数short_words(line),该函数接受单词列表类型的参数行,并返回一个单词频率小于4的字典。键是3个或更少字符的单词,值是这些单词的频率。 例如,当使用参数['a','the','a','an','many','a','of','the','less']调用时,该函数将返回{'a':3','an':1','the':2','of':1}集合。计数器: import collections def short_words(line): return dict(collect
例如,当使用参数
['a','the','a','an','many','a','of','the','less']
调用时,该函数将返回{'a':3','an':1','the':2','of':1}
集合。计数器
:
import collections
def short_words(line):
return dict(collections.Counter([x for x in line if len(x) < 4]))
导入集合
def短_字(行):
return dict(collections.Counter([x代表x,如果len(x)<4]))
不允许进口
def short_words(line):
nList = [x for x in line if len(x) < 4]
return {word: nList.count(word) for word in set(nList)}
def短词(行):
nList=[x表示x,如果len(x)<4]
返回{word:nList.count(word)for set(nList)}
欢迎来到SO。在SO上发布时,请确保包含您编写的所有相关代码。因此,这不是一个代码编写服务。