我需要: 1.形成二元对并将它们存储在列表中 2.找到其中有最高频率的前3个二元组的id的总和
我有一个句子列表:
[['22574999', 'your message communication sent']
, ['22582857', 'your message be delivered']
, ['22585166', 'message has be delivered']
, ['22585424', 'message originated communication sent']]
这是我做的:
for row in messages:
sstrm = list(row)
bigrams=[b for l in sstrm for b in zip(l.split(" ")[:1], l.split(" ")[1:])]
print(sstrm[0],bigrams)
产生:
22574999 [('your', 'message')]
22582857 [('[your', 'message')]
22585166 [('message', 'has')]
22585424 [('message', 'originated')]
我想要的是:
22574999 [('your', 'message'),('communication','sent')]
22582857 [('[your', 'message'),('be','delivered')]
22585166 [('message', 'has'),('be','delivered')]
22585424 [('message', 'originated'),('communication','sent')]
我想得到以下结果 结果:
频率最高的前三名双子座:
('your', 'message') :2
('communication','sent'):2
('be','delivered'):2
最高频率排名前3位的双子座的身份总和:
('your', 'message'):2 Is included (22574999,22582857)
('communication','sent'):2 Is included(22574999,22585424)
('be','delivered'):2 Is included (22582857,22585166)
感谢您的帮助!
答案 0 :(得分:1)
首先我要指出的是, bigrams 是两个相邻元素的序列。
例如,狐狸跳过懒狗的大人物"是:
[("the", "fox"),("fox", "jumped"),("jumped", "over"),("over", "the"),("the", "lazy"),("lazy", "dog")]
可以使用 inverted index 对此问题进行建模,其中双字母组件是发布内容,而ids组是发布列表。
def bigrams(line):
tokens = line.split(" ")
return [(tokens[i], tokens[i+1]) for i in range(0, len(tokens)-1)]
if __name__ == "__main__":
messages = [['22574999', 'your message communication sent'], ['22582857', 'your message be delivered'], ['22585166', 'message has be delivered'], ['22585424', 'message originated communication sent']]
bigrams_set = set()
for row in messages:
l_bigrams = bigrams(row[1])
for bigram in l_bigrams:
bigrams_set.add(bigram)
inverted_idx = dict((b,[]) for b in bigrams_set)
for row in messages:
l_bigrams = bigrams(row[1])
for bigram in l_bigrams:
inverted_idx[bigram].append(row[0])
freq_bigrams = dict((b,len(ids)) for b,ids in inverted_idx.items())
import operator
top3_bigrams = sorted(freq_bigrams.iteritems(), key=operator.itemgetter(1), reverse=True)[:3]
输出
[(('communication', 'sent'), 2), (('your', 'message'), 2), (('be', 'delivered'), 2)]
虽然这段代码可以大量优化,但它可以为您提供理念。
答案 1 :(得分:0)
此行中有错误:
bigrams=[b for l in sstrm for b in zip(l.split(" ")[:1], l.split(" ")[1:])]
在zip的第一个参数中,您将使用[:1]
停在列表的第一个元素。你想获得除最后一个元素之外的所有元素,它们对应于[:-1]
。
所以这条线应该是这样的:
bigrams=[b for l in sstrm for b in zip(l.split(" ")[:-1], l.split(" ")[1:])]