我正在制作一个短文生成器,通过从示例文本中创建一个有向图,其中单词是节点,单词和后面的任何单词之间都有有向边。我正在通过一个字典来形成节点,但是程序似乎不会读取第一个单词之后出现的单词
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])等等。 你可以这样做:相关问题 更多 >
编程相关推荐