我有两个string列表:

(Pdb) word_list1
['first', 'sentence', 'ant', 'first', 'whatever']
(Pdb) word_list2
['second', 'second', 'heck', 'anything', 'youtube', 'gmail', 'hotmail']


我想为每个单词的两个集合中的每个集合计算单词并集的概率分布。

(Pdb) print list(set(word_list1) | set(word_list2))
['hotmail', 'anything', 'sentence', 'maybe', 'youtube', 'whatever', 'ant', 'second', 'heck', 'gmail', 'first']
(Pdb) len(list(set(word_list1) | set(word_list2)))
11


因此,我想要两个长度为11的向量,每个单词列表一个。

最佳答案

因此,您需要更多包含11个元素的字典,如果要查找频率,请使用Counter而不是set操作:

from collections import Counter

n   = len(l1) + len(l2)
dic = dict(Counter(l1) + Counter(l2))

# for the first list
{k:round(v/n,2) if k in l1 else 0 for k,v in dic.iteritems()}

#{'ant': 0.09,
# 'anything': 0,
# 'first': 0.18,
# 'gmail': 0,
# 'heck': 0,
# 'hotmail': 0,
# 'second': 0,
# 'sentence': 0.09,
# 'whatever': 0.09,
# 'youtube': 0}

10-07 12:16
查看更多