【问题标题】:Python - ValueError: invalid literal for int() with base 10: 'hello'Python - ValueError:int() 的无效文字,基数为 10:'hello'
【发布时间】:2017-08-15 22:19:56
【问题描述】:

我在 python 2.7 上收到以下错误。 'Hello' 是文本文件中一行中的最后一个单词。以下解决方案对我不起作用ValueError: invalid literal for int() with base 10: 'Height (mm)'

ValueError: invalid literal for int() with base 10: 'hello.'

执行以下代码时

import io

with io.open(r'C:\Python\Data\somefile.txt','r+') as f:
    bytecolumn = (line.rsplit(None,1)[1] for line in f)
    bytes = (int(x) for x in bytecolumn if x != '-')
    print('Total', sum(bytes))

我也尝试过使用

int(float(x))

但它会引发错误

ValueError: could not convert string to float: hello.

P.S - 我在堆栈溢出中查看了所有类似的问题,但没有一个解决方案有效。这就是发帖的原因。请不要标记重复

编辑:我正在尝试查找单词的大小。这就是我进行求和并调用生成器的原因

【问题讨论】:

  • 错误是非常明确,您有时会获取文本hello 并尝试将其转换为整数。毫不奇怪,尝试将hello 转换为浮点数也会失败。 使用调试器,打印有问题的行,这应该可以帮助您找出问题所在
  • 为什么要尝试将 Hello 转换为整数?你希望得到什么结果?
  • 完全不清楚您要做什么。你似乎明白最后一个字符串是"hello",所以我不确定你到底想要达到什么目的......
  • @juanpa.arrivillaga 我已经更新了帖子。我试图从文件对象(f)中总结每一行最后一个单词的大小
  • @Joe_12345 呃,你说的大小是指len(word)

标签: python python-2.7


【解决方案1】:

以下解决方案有效。我们需要使用

而不是使用 int(x)
len(x.encode('utf-8'))

所以最终代码更新为

import io

with io.open(r'C:\Python\Data\somefile.txt','r+') as fp:
    bytecolumn = (line.rsplit(None,1)[1] for line in fp)
    bytes = ( len(x.encode('utf-8'))  for x in bytecolumn if x != '-')
    print('Total', sum(bytes))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-11
    • 2021-08-06
    • 2018-09-05
    • 2021-12-18
    相关资源
    最近更新 更多