我需要:
1.形成双字母对,并存储在列表中
2.找到ID的总和,其中ID的总和中前3个频率最高

我有一个句子列表:

[['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')]


我想得到以下结果
结果:

频率最高的前3个二元组:

('your', 'message') :2
('communication','sent'):2
('be','delivered'):2


ID的总和,其中出现频率最高的前3个双字母组:

('your', 'message'):2           Is included (22574999,22582857)
('communication','sent'):2      Is included(22574999,22585424)
('be','delivered'):2            Is included (22582857,22585166)


谢谢你的帮助!

最佳答案

我想指出的第一件事是二元组是两个相邻元素的序列。

例如,“狐狸跳过了懒狗”的二元组是:

[("the", "fox"),("fox", "jumped"),("jumped", "over"),("over", "the"),("the", "lazy"),("lazy", "dog")]

可以使用inverted index来模拟此问题,其中双字是发布,而ID集是发布列表。

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)]


尽管可以大量优化此代码,但它可以为您提供想法。

关于python - 在句子列表中形成单词的双字母组合,并使用python计算双字母组合,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46566402/

10-10 16:09