【发布时间】:2021-02-13 05:24:36
【问题描述】:
我试图循环包含字典的 txt 文件
我的代码将其作为字符串读取也尝试将这些 txt 文件更改为 json,但由于这些单词是单引号,所以它说:
期望用双引号括起来的属性名称
代码
for jfile in file_txt.glob('*.txt')
with jfile.open('r') as ifile:
lines_dict=ifile.read()
for page, word in lines_dict.items():
lines = convert_text_to_lines(word)
错误
for page, word in lines_dict.items():
AttributeError: 'str' object has no attribute 'items'
我的 txt 文件示例
{1: [((86, 27, 168, 50), 'haha'), ((85, 53, 195, 63), ' work for you.'), ((323, 49, 408, 57), 'Total due'), ((534, 42, 590, 59), '4.10'), ((323, 66, 515, 77), ' do not need to make')}
【问题讨论】:
-
文件包含的是一个字典的字符串表示 - 不是一个实际的字典。这有点像看一本书的图片——你不能翻页,但你可以用图片找到真正的书。在您的情况下,您必须首先将文件内容转换回实际的字典,例如通过
ast.literal_eval. -
这是您文件的实际内容吗?你确定没有,比如说,在结尾处没有结尾的
]吗?
标签: python json python-3.x dictionary