我决定为 Telegram 制作一个具有马尔可夫链的机器人,为了训练马尔可夫链,我下载了我一群朋友的聊天记录,并制作了一个脚本来过滤和分离来自该组的消息,但出现了一些错误出现在JSOM中,由于文件非常大(7193776行),我编写了一个脚本来自动纠正json,因为手动纠正它是不可行的,我处理了异常,它返回了这个编码错误:
It was not possible correct the JSON: Extra data: line 1 column 3 (char 2)
JSON decoding error on line: Extra data: line 1 column 7 (char 6)
我认为这是因为 JSON 每行有多个对象,我想知道你的意见,你认为它可能是什么?
这是脚本中的一段代码(我不会完整地介绍它,以免这篇文章太长):
item = json.loads(line)
return item
except json.JSONDecodeError as e:
print(f"Unable to fix JSON: {e}")
return None
# Open input file
with open(input_file, 'r', encoding='utf-8') as in_file:
for line in in_file:
# Tenta corrigir a linha
fixed_line = fix_json_line(line.strip())
if fixed_line:
fixed_messages.append(fixed_line)
else:
unfixed_lines.append(line)
# Saves corrected messages to a new JSON file
with open(output_file, 'w', encoding='utf-8') as out_file:
json.dump(fixed_messages, out_file, ensure_ascii=False, indent=2)
# Saves lines that could not be corrected in a separate file
if unfixed_lines:
with open('unfixed_lines.txt', 'w', encoding='utf-8') as unfixed_file:
unfixed_file.writelines(unfixed_lines)
print(f"Lines that could not be corrected were saved in 'unfixed_lines.txt'")
else:
print("All lines were successfully corrected.")
print(f"Lines corrected and saved in {output_file}")
我已经尝试过搜索,但由于错误的描述非常模糊(我无法进一步指定错误)Google 返回了几个可能的错误,但我不知道它可能是什么,我询问 GPT 聊天,但有些天好像它不能正常工作。 .. 我问了我的技术课程老师,但他无法回答我!这是 json 格式的示例:
{
"id": 610775,
"type": "message",
"date": "2024-06-27T13:55:13",
"date_unixtime": "1719507313",
"from": "Swelve",
"from_id": "user5957514107",
"reply_to_message_id": 610761,
"text": "antes de pisar numa universidade ele deveria revisar esse português dele",
"text_entities": [
{
"type": "plain",
"text": "antes de pisar numa universidade ele deveria revisar esse português dele"
}
]
},
{
"id": 610776,
"type": "message",
"date": "2024-06-27T13:56:31",
"date_unixtime": "1719507391",
"from": "Old dirty bastard λ",
"from_id": "user1758042831",
"text": "No mínimo",
"text_entities": [
{
"type": "plain",
"text": "No mínimo"
}
]
}
]
}
从我的角度来看,json 没有任何问题,但由于我刚刚开始使用 python 和机器学习,我可能是非常错误的(之前我是一个热爱函数式编程的嬉皮士,但在我的国家,有更多的 python 工作)所以我开始学习Python以获得工作机会)我问这个是因为为了纠正错误我首先必须知道错误是什么,而我什至不知道......
json 模块旨在解析整个 json 对象,而不是评估单行。
这是因为 Json 中的每个空格都是可选的,并且可以有任意多个空格。 因为 json 模块的目标不是纠正损坏的数据。目标是将有效的 json-object 转换为 python-dict,或将有效的 json-objects 的 json-array 转换为 python-dicts 的 python-list。 (或反之亦然)
因此,您应该更正要解析的 json 文件(不使用 json-module),然后将整个文件传递给 json.load 方法。
也就是说,我认为您只需要用方括号 [] 将整个文件括起来。据我所知, python-json-module 估计一个 json-object 或 json-objects 的 json-array。 json 数组之外不是多个逗号分隔的 json 对象
但是,请记住,我只能猜测,因为您逐行传递,而没有记录发生错误的 json 行。 如果没有整个脚本,我无法重建您的问题。