繁体   English   中英

用计算值创建字典

[英]Creating a dictionary with calculated values

我有一个很大的文本字符串,我想创建一个字典,其中的键=字符串中的一对单词(必须经过所有可能的组合),值=给定单词对的频率。 因此,它是一个2D矩阵,每个矩阵元素都是一个数字(行和列之间的交叉对的频率。该对中单词的位置无关紧要:例如,如果ridebike = 4(频率)然后也是rideride = 4

最终结果是填充矩阵,然后选择N个顶部对。

我是刚开始使用文本字符串和Python的新手,我无可救药地迷路了(“代码”中的循环也太多了)

这就是我所拥有的(删除停用词和标点符号之后):

textNP = 'stopped traffic bklyn  bqe  278 wb manhattan brtillary stx29  wb  cadman pla  hope  oufootball makes safe manhattan kansas tomorrow  boomersooner  beatwildcats  theyhateuscuztheyaintus  hatersgonnahate rt  bringonthecats  bring cats exclusive  live footage oklahoma trying get manhattan  http  colktsoyzvvz rt  jonfmorse  bring cats exclusive  live footage oklahoma trying get manhattan'

一些代码(不完整和错误):

txtU = set(textNP)
lntxt = len(textNP)
lntxtS = len(txtU)

matrixNP = {}

for b1, i1 in txtU: 
    for b2, i2 in txtU:
        if i1< i2:
            bb1 = b1+b2
            bb2 = b2+b1

            freq = 0

            for k in textNP:
                for j in textNP:
                    if k < j:

                        kj = k+j
                        if kj == bb1 | kj == bb2:

                            freq +=1

            matrixNP[i1][i2] = freq
            matrixNP[i2][i1] = freq

        elif i1 == i2: matrixNP[i1][i1] = 1

我确信存在很多循环的问题之一是错误的。 另外,我不确定如何将计算键(单词的连接)分配给字典(我认为我正确地获得了值)

文本字符串不是完整的产品:使用各种正则表达式可以清除数字和其他一些东西

非常感谢您的帮助!

您是否正在寻找2个单词的所有组合,如果可以的话,可以使用itertools.combinationscollections.Counter来做您想要的事情:

>>> from itertools import combinations
>>> from collections import Counter
>>> N = 5
>>> c = Counter(tuple(sorted(a)) for a in combinations(textNP.split(), 2))
>>> c.most_common(N)
[(('manhattan', 'rt'), 8),
 (('exclusive', 'manhattan'), 8),
 (('footage', 'manhattan'), 8),
 (('manhattan', 'oklahoma'), 8),
 (('bring', 'manhattan'), 8)]

或者,您要查找所有成对的连续单词,然后可以创建成对函数:

>>> from itertools import tee
>>> from collections import Counter
>>> def pairwise(iterable):
...     a, b = tee(iterable)
...     next(b, None)
...     return zip(a, b)    # itertools.izip() in python2
>>> N = 5
>>> c = Counter(tuple(sorted(a)) for a in pairwise(textNP.split()))
>>> c.most_common(N)
[(('get', 'manhattan'), 2),
 (('footage', 'live'), 2),
 (('get', 'trying'), 2),
 (('bring', 'cats'), 2),
 (('exclusive', 'live'), 2)]

我也没有在列表中看到骑自行车。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM