【问题标题】:Python 3.5.1 - ValueError: invalid literal for int() with base 10Python 3.5.1 - ValueError: int() 以 10 为底的无效文字
【发布时间】: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


    【解决方案1】:

    您在numberList 中似乎有一个空字符串。原因是文本的分裂。

    请看下面的例子:

    >>> 'xx  yy'.split()
    ['xx', 'yy']
    >>> 'xx  yy'.split(' ')
    ['xx', '', 'yy']
    

    如果你使用分隔符,你总是会得到一个结果,即使你分割一个空字符串。

    >>> ''.split(' ')
    ['']
    

    引用split的文档。

    如果 sep 未指定或为 None,则使用不同的分割算法 应用:连续空白的运行被视为单个 分隔符,结果开头不包含空字符串 如果字符串有前导或尾随空格,则结束。所以, 拆分空字符串或仅包含空格的字符串 使用 None 分隔符返回 []。

    所以目前你使用split(" "),但你应该使用不带参数的split()

    【讨论】:

    • 谢谢。这是完美的:)
    【解决方案2】:

    正如您的回溯所指定的,您正在传入一个空字符串 (''),并尝试将其设为整数。您可以在之前测试空值

    newoutput = (wordDictionary[int(numbers)]) + " "
    

    或者将它后面的语句包装在 try/catch 中。

    但是,最好的解决方案可能是在计算之前阻止将空字符串添加到您的 numbersList 列表中。

    【讨论】:

      【解决方案3】:

      您将一个空字符串传递给 int() 方法。

      这是说它不知道如何解析一个空字符串。 回显打印并检查您的程序为该方法提供的内容将最大程度地帮助您。

      这里的数字是一个空字符串。

      【讨论】:

        猜你喜欢
        • 2018-09-09
        • 2020-01-04
        • 2010-12-22
        • 2011-07-07
        • 2019-10-14
        • 2022-05-19
        相关资源
        最近更新 更多