python - 为什么我在解析时收到此错误?

标签 python

我正在读取一个文本文件并将其转换为 python 字典:

文件看起来像这样,带有标签字:

20001   World Economies

20002   Politics

20004   Internet Law

20005   Philipines Elections

20006   Israel Politics

20007   Science

这是读取文件并创建字典的代码:

def get_pair(line):
  key, sep, value = line.strip().partition("\t")
  return int(key), value


with open("mapped.txt") as fd:    
           d = dict(get_pair(line) for line in fd)
print(d)

当我打印 d 的内容时,我收到 {}。 此外,我收到此错误:

Traceback (most recent call last):
  File "predicter.py", line 23, in <module>
    d = dict(get_pair(line) for line in fd)
  File "predicter.py", line 23, in <genexpr>
    d = dict(get_pair(line) for line in fd)
  File "predicter.py", line 19, in get_pair
    return int(key), value
ValueError: invalid literal for int() with base 10: ''

这是什么意思?我的文件中确实有内容,我不确定为什么它没有被读取。

最佳答案

这意味着 key 为空,这又意味着您有一行开头带有 \t 选项卡的行或空行:

>>> '\tScience'.partition('\t')
>>> ''.partition('\t')
('', '', '')

我的猜测是后者;您可以在生成器表达式中跳过此类行:

d = dict(get_pair(line) for line in fd if '\t' in line.strip())

因为 line.strip() 返回没有前导和尾随空格的行,空行或开头只有一个制表符的行会导致字符串中完全没有制表符。这不会处理所有情况,但您也可以删除传递给 get_pair() 的值:

d = dict(get_pair(line.strip()) for line in fd if '\t' in line.strip())

关于python - 为什么我在解析时收到此错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35669126/

相关文章:

python - 贪婪的正则表达式回顾

python - 从列表python中找到最大平均值

python - sip 安装成功后安装 PyQt(用于 pyuic4) : error: PyQt-x11-gpl-4. 11 安装

python - 如何在 Ironpython (Python.net) 中得到 'print' 的除法结果?

python - 使用两个版本的 Python (Windows) 安装 IPython

python - 如何级联删除到 SqlAlchemy 中的多个表?

python - 如何将关卡布局保存在变量中

python - 将缺失的时间步添加到 Pandas 数据框中

python - Tensorflow Executor 无法创建内核。未实现: Cast string to float is not supported

python - Sobel 运算符的 Opencv 意外输出