我有一个很大的文本字符串,我想创建一个字典,其中键=字符串中的一对单词(必须遍历所有可能的组合),值=给定单词对的频率。因此,它是一个 2D 矩阵,每个矩阵元素都是一个数字(彼此交叉的列和行对的频率。对中单词的位置无关:例如,如果ridebike = 4(频率)然后骑自行车= 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.combinations
和 collections.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)]
我在列表中都看不到骑自行车。
关于python - 使用计算值创建字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33182811/