我正在尝试使用csv文件创建条形图,并且不断收到此消息。我的数据几乎都是整数。
for item in text_list :
pieces_list = item.strip().split(',')
print(pieces_list)
Month_list.append(pieces_list[0])
Total_list.append(int(pieces_list[1]))
发布于 2021-06-12 11:10:14
字符串'"1"'
由三个单独的字符组成:{ ", 1, " }
,并且"
在计算整数的上下文中无效。这无疑是由于CSV允许在字段周围使用引号造成的:
"has quotes", does not have quotes, "1"
您需要首先去掉字符串开头和结尾的双引号(如果它们在那里)。例如:
>>> withq = '"42"'
>>> int(withq)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '"42"'
>>> int(withq.strip('"'))
42
请记住,这将剥离字符串开头和结尾的所有"
字符,因此""""""""42"""
仍将作为42
出现。replace()
将替换字符串中任意位置的引号。为了绝对安全,一个更好的选择可能是一个函数来为你做繁琐的工作:
# Get integer from a string CSV field.
# If first and last characters are both '"', convert the inner bit.
# Otherwise, convert the whole thing.
# May throw if bit being converted in not valid integer.
def csv_int(field):
if len(field) >= 2 and field[0] == '"' and field[-1] == '"':
return int(field[1:-1])
return int(field)
发布于 2021-06-12 11:11:50
看起来我在执行以下操作时遇到了同样的错误
print(int('"1"'))
注意数字1
周围的"
。
ValueError:基数为10的int()的文本无效:‘“1”“
因此,我建议您在此字符串上使用replace()
或其他方法来消除这种情况。
print(int('"1"'.replace('"','')))
输出
1
https://stackoverflow.com/questions/67945301
复制相似问题