gpt4 book ai didi

Python JSON数据加载令人困惑的 "expecting , delimiter"错误

转载 作者:行者123 更新时间:2023-11-30 22:15:51 32 4
gpt4 key购买 nike

尝试实现此代码并不断收到以下错误。我已经搜索并尝试了一切,但没有什么能让我过去。

import json
import sys
import re
import os
reload(sys)
sys.setdefaultencoding('utf8')
path = '/Users/.../' #(The actual path is in my code)
textfiles = []
for root, dirs, files in os.walk(r'/Users/.../'):
for file in files:
if file.endswith(".txt"):
textfiles.append(file)
for filename in textfiles:
with open(path + filename) as json_data:
data = json.load(json_data)
opinion = data['plain_text']
f = open(path + filename, 'w')
f.write(opinion)
f.close()

然后,我不断收到此错误:

ValueError: Expecting , delimiter: line 17 column 3 (char 765)

最佳答案

显然你的问题出在 JSON 文件中。但是是哪一个?哪里??

如果您放入 try/except 子句,您可以记录并查看哪些文件导致问题,以便您可以更轻松地进行调试。

import json
import sys
import re
import os
reload(sys)
sys.setdefaultencoding('utf8')
path = '/Users/.../' (The actual path is in my code)
textfiles = []
for root, dirs, files in os.walk(r'/Users/.../'):
for file in files:
if file.endswith(".txt"):
textfiles.append(file)
for filename in textfiles:
try:
with open(path + filename) as json_data:
data = json.load(json_data)
opinion = data['plain_text']
f = open(path + filename, 'w')
f.write(opinion)
f.close()
except ValueError as e:
print(filename) # Gives the filename
print(e) # Gives the location of the problem in the file

它还应该继续遍历文件并提供有问题的错误。

您甚至可以保存到 log.txt 以便稍后处理..

这是一个小例子

lst = [1, 2, '3', 4, 5]

for i in lst:
try:
l = 123 + i
print(l)
except Exception as e:
print(e)

输出:

124
125
unsupported operand type(s) for +: 'int' and 'str'
127
128

关于Python JSON数据加载令人困惑的 "expecting , delimiter"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50166308/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com