Skip to main content
 首页 » 编程设计

python之字典包含文本文件中的单词作为键,所有下一个单词的列表作为值

2024年10月01日7kuangbin

我无法理解这背后的逻辑。

1.) 首先,我从该文本文件中读取了一个去除了标点符号和空格的文本文件:

The sun is bright & the moon glows. 
The dog barks while the cat meows. 
My dog is dark, dark as crows. 

2.) 阅读完这个文本文件后,我假设有一个字典,其中一个词作为键,下一个词作为值,如下所示:

{'the':['sun','moon','dog','cat'], 'sun':['is'], 'is':['bright','dark'], 'moon':['glows'],'glows':['the'],  
 'dog':['barks','is'], 'barks':['while'],'while':['the'], 'cat':['meows'],'meows':['my'], 'my':['dog'],  
 'dark':['dark','as'], 'as':['crows'],  
 'bright':['the'], 'crows':[]} 

最后两项是特例。 "crows" 有一个空列表,因为它是文本文件中的最后一个词。

我不确定这背后的逻辑,但我似乎无法理解这一点。

我的第一个方法是创建一个包含所有单词的巨大列表,然后从列表中挑选和提取以形成几个较小的列表。

请您参考如下方法:

您可以链接一些字符串转换以去除标点符号,然后在转换为小写后拆分字符串(The 与 the)。

然后,将单词列表与同一列表的移位副本交错并对其进行迭代。

将值附加到字典元素,因此键是当前单词,值是后面单词的列表。问题是 crows 不在列表中。所以手动添加最后一个词。

from collections import defaultdict 
import string 
 
s = "The sun is bright & the moon glows. The dog barks while the cat meows. My dog is dark, dark as crows." 
s = s.translate({ord(x):None for x in string.punctuation}).lower().split() 
 
c = defaultdict(list) 
 
for cw,nw in zip(s,s[1:]): 
    c[cw].append(nw) 
 
c[s[-1]] = []  # last word of the sentence, special case 
print(c) 

结果:

defaultdict(<class 'list'>, {'is': ['bright', 'dark'], 'moon': ['glows'], 
 'cat': ['meows'], 'glows': ['the'], 'meows': ['my'], 'crows': [],  
'bright': ['the'], 'while': ['the'], 'the': ['sun', 'moon', 'dog','cat'],   
'as': ['crows'], 'dog': ['barks', 'is'], 'sun': ['is'], 'my':      
['dog'], 'dark': ['dark', 'as'], 'barks': ['while']})