程序无法识别单词 python 的多次出现(在 linux 上)
program not recognizing multiple occurrences of word python (on linux)
我正在通过从示例文本创建有向图来制作论文生成器,其中单词是节点,并且单词和跟随它的任何单词之间存在有向边。我正在通过字典形成节点,但程序似乎没有读取第一个单词之后的出现。
tH = {}
with open('ex','r') as f:
for line in f:
valHold = [w.lower() for w in line.split()]
for x in valHold:
if x not in tH:
tH[x] = []
if x != valHold[-1] and valHold[valHold.index(x) + 1] not in tH[x]:
tH[x].append(valHold[valHold.index(x) + 1])
print(tH)
我希望输出是
{'the' : ['sun', 'moon'], 'sun' : ['the'], 'moon' : []}
当文件 'ex' 包含字符串时
'the sun the moon'
但输出是
{'the' : ['sun'], 'sun' : ['the'] 'moon' : []}
而不是 for x in valHold:
遍历 valHold 中的每个单词,您需要每隔一个单词遍历一次,即 x = valHold[0](store valHold[1]),x =valHold[2 ](store valHold[3]) 等等。
你可以这样做:
for i in range(0, len(valHold), 2):
x = valHold[i]
if x not in tH:
tH[x] = []
if x != valHold[-1] and valHold[i + 1] not in tH[x]:
tH[x].append(valHold[i + 1])
我正在通过从示例文本创建有向图来制作论文生成器,其中单词是节点,并且单词和跟随它的任何单词之间存在有向边。我正在通过字典形成节点,但程序似乎没有读取第一个单词之后的出现。
tH = {}
with open('ex','r') as f:
for line in f:
valHold = [w.lower() for w in line.split()]
for x in valHold:
if x not in tH:
tH[x] = []
if x != valHold[-1] and valHold[valHold.index(x) + 1] not in tH[x]:
tH[x].append(valHold[valHold.index(x) + 1])
print(tH)
我希望输出是
{'the' : ['sun', 'moon'], 'sun' : ['the'], 'moon' : []}
当文件 'ex' 包含字符串时
'the sun the moon'
但输出是
{'the' : ['sun'], 'sun' : ['the'] 'moon' : []}
而不是 for x in valHold:
遍历 valHold 中的每个单词,您需要每隔一个单词遍历一次,即 x = valHold[0](store valHold[1]),x =valHold[2 ](store valHold[3]) 等等。
你可以这样做:
for i in range(0, len(valHold), 2):
x = valHold[i]
if x not in tH:
tH[x] = []
if x != valHold[-1] and valHold[i + 1] not in tH[x]:
tH[x].append(valHold[i + 1])