簡體   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