【发布时间】:2016-10-17 00:22:44
【问题描述】:
我的程序所做的是
- 造句
- 制作字典并将其放入外部 txt 文件中
- 制作一个数字列表,指示哪些单词在哪些位置
- 使用数字和字典重新创建原始句子并将其放入外部 txt 文件中
但是,我在重新创建句子时收到此错误消息:
line 22, in <module>
newoutput = (wordDictionary[int(numbers)]) + " "
ValueError: invalid literal for int() with base 10: ''
这是我的代码
sentence = input("What is your sentence? ")
splitWords = sentence.split()
wordPositions = ""
wordDictionary = {}
for positions, words in enumerate(splitWords):
if words not in wordDictionary:
wordDictionary[words] = positions+1
wordPositions = wordPositions + str(wordDictionary[words]) + " "
fileName = input("What would you like to call your dictionary .txt file? ")
file = open (fileName + ".txt", "w")
for words in wordDictionary:
output = words + "\t" + str(wordDictionary[words]) + "\n"
file.write(output)
file.close()
numberList = wordPositions.split(" ")
wordDictionary = {y:x for x,y in wordDictionary.items()}
fileName2 = input("What would you like to call your sentance .txt file? ")
file = open(fileName2 + ".txt", "w")
for numbers in numberList:
newoutput = (wordDictionary[int(numbers)]) + " "
file.write(newoutput)
file.close()
如何解决此错误消息?
谢谢你的帮助:)
【问题讨论】:
标签: python string python-3.x dictionary int