使用计算值创建字典

2024-09-28 05:24:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个大的文本字符串,我想创建一个字典,其中的键=字符串中的一对单词(必须经过所有可能的组合),值=给定单词对的频率。因此,它是一个2D矩阵,每个矩阵元素是一个数字(列和行中的一对相互交叉的频率)。单词在一对中的位置是不相关的:例如,如果ridebike=4(频率),那么bikeride=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

其中一个问题,我确信有许多循环是错误的。另外,我不知道如何将计算键(单词的串联)分配给字典(我想我得到的值是正确的)

文本字符串不是一个完整的产品:它将从数字和其他一些东西中清除,并使用各种正则表达式

非常感谢您的帮助!你知道吗


Tags: 字符串in文本for矩阵单词b1频率
1条回答
网友
1楼 · 发布于 2024-09-28 05:24:31

您是否正在查找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)]

我也不认为骑自行车在名单上。你知道吗

相关问题 更多 >

    热门问题