【问题标题】:bigram occurences to dictionary python字典python的二元组出现
【发布时间】:2020-03-28 19:35:26
【问题描述】:

我想遍历列表:

inc_list = ['one', 'two', 'one', 'three', 'two', 'one', 'three']

并创建一个字典,显示相邻单词的所有二元组及其出现次数,同时将倒序组合计数为相等,因此倒序组合并排除相同的单词组合。 所以..'one', 'two'....'two', 'one'.. 都应该添加到字典中('one', 'two') 的计数中。

预期输出:

{('one', 'two'): 3, ('one', 'three'): 2, ('two', 'three'): 1}

到目前为止,我已经尝试过:

import itertools
from collections import Counter

inc_list = ['one', 'two', 'one', 'three', 'two', 'one', 'three',]

coocurences = dict(Counter(itertools.combinations(inc_list, 2)))

print(coocurences)

这显然计算了所有组合可能性,同时包括反向和相同的单词组合,所以不是我要找的。​​p>

itertools 中是否有一个工具可以更接近我想要的输出?

我找到了很多关于共现矩阵的信息,但是我更喜欢字典作为输出。

【问题讨论】:

  • 您如何区分包含的组合?我的意思是什么时候是 one_two,什么时候是 two_one..

标签: python-3.x dictionary combinations counter find-occurrences


【解决方案1】:

根据我的评论,如果您只想添加一对,则需要定义对的顺序。这是一种可能性:

from collections import Counter

inc_list = ['one', 'two', 'one', 'three', 'two', 'one', 'three',]

bigrams = Counter()
for previous, current in zip(inc_list, inc_list[1:]):
    opt1 = (f"{previous}", f"{current}")
    opt2 = (f"{current}", f"{previous}")
    if opt2 not in bigrams:
        bigrams[opt1] += 1
        continue
    bigrams[opt2] += 1
coocurences = dict(bigrams)
print(coocurences)

输出:

{('one', 'two'): 3, ('one', 'three'): 2, ('three', 'two'): 1}

【讨论】:

    【解决方案2】:

    感谢您的快速回复和中肯的建议。我对其进行了一些修改,以提供我所需要的。

    from collections import Counter
    
    inc_list = ['one', 'two', 'one', 'three', 'two', 'one', 'three',]
    
    bigrams = Counter()
    for previous, current in zip(inc_list, inc_list[1:]):
        opt1 = f"{previous}", f"{current}"
        opt2 = f"{current}", f"{previous}"
        if opt2 not in bigrams:
            bigrams[opt1] += 1
            continue
        bigrams[opt2] += 1
    coocurences = dict(bigrams)
    print(coocurences)
    

    这就出来了:

    {('one', 'two'): 3, ('one', 'three'): 2, ('three', 'two'): 1}
    

    谢谢:)

    【讨论】:

    • 是的,很抱歉我错过了格式化细节。我自己一直在研究_分离的二元组。更新以匹配您请求的输出。接受? :)
    • 没问题。你的建议使它起作用,所以所有的道具都给你。祝你星期天愉快
    猜你喜欢
    • 2017-09-17
    • 2022-01-17
    • 1970-01-01
    • 2020-04-03
    • 1970-01-01
    • 2018-02-23
    • 2019-05-09
    • 2021-03-13
    • 1970-01-01
    相关资源
    最近更新 更多