计算嵌套列表中的频率
我正在尝试用一个字典来计算单词的出现频率,字典里面是嵌套列表。每个嵌套列表代表一句话,里面分解成每个单词。此外,我还想删除专有名词和句子开头的小写单词。这样做真的能去掉专有名词吗?
x = [["Hey", "Kyle","are", "you", "doing"],["I", "am", "doing", "fine"]["Kyle", "what", "time" "is", "it"]
from collections import Counter
def computeFrequencies(x):
count = Counter()
for listofWords in L:
for word in L:
count[word] += 1
return count
但是它返回了一个错误:不可哈希的类型:'list'
我想要的结果是这样的,字典外面没有Counter():
{"hey": 1, "how": 1, "are": 1, "you": 1, "doing": 2, "i": , "am": 1, "fine": 1, "what": 1, "time": 1, "is": 1, "it": 1}
2 个回答
2
问题在于你对 L
进行了两次循环。
把里面的循环替换成:
for word in L:
用:
for word in listofWords:
不过,如果你想要更“python风格”的写法,可以看看 @thefourtheye 的解决方案。
7
因为你的数据是嵌套的,所以你可以用 chain.from_iterable
来把它展开,像这样
from itertools import chain
from collections import Counter
print Counter(chain.from_iterable(x))
# Counter({'doing': 2, 'Kyle': 2, 'what': 1, 'timeis': 1, 'am': 1, 'Hey': 1, 'I': 1, 'are': 1, 'it': 1, 'you': 1, 'fine': 1})
如果你想用生成器表达式的话,可以这样做
from collections import Counter
print Counter(item for items in x for item in items)
如果你不想用 Counter,那你可以用普通的字典,像这样
my_counter = {}
for line in x:
for word in line:
my_counter[word] = my_counter.get(word, 0) + 1
print my_counter
你也可以使用 collections.defaultdict
,像这样
from collections import defaultdict
my_counter = defaultdict(int)
for line in x:
for word in line:
my_counter[word] += 1
print my_counter
好吧,如果你只是想把 Counter
对象转换成 dict
对象(我觉得这其实没必要,因为 Counter
本身就是一个字典。你可以像使用普通字典一样访问键值、遍历、删除和更新 Counter
对象),你可以参考 bsoist 的建议,
print dict(Counter(chain.from_iterable(x)))