程序无法识别多次出现的单词python(在linux上)

2024-09-28 03:22:37 发布

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

我正在制作一个短文生成器,通过从示例文本中创建一个有向图,其中单词是节点,单词和后面的任何单词之间都有有向边。我正在通过一个字典来形成节点,但是程序似乎不会读取第一个单词之后出现的单词

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' : []}

Tags: theinforindexif节点linenot
1条回答
网友
1楼 · 发布于 2024-09-28 03:22:37

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])

相关问题 更多 >

    热门问题