使用try-except迭代编写文本文件的问题



以下是我的代码-

for file in files:
k+=1
f = str(file)
with open(f) as data:
post = json.load(data)
l+=1
try:
query = post["title"]+" - "+cleanText(html.unescape(post["replies"][0]["text"]))
queries.write(query+'n')
i+=1
except:
j+=1
pass
for i in range(1,len(docs)):
docs[i] = re.sub("[^a-zA-Z]", " ",str(docs[i]))
document = cleanText(html.unescape(docs[i]))
documents.write(document+'n')
queries.close()
documents.close()

我总共有7000个文件。由于我只读取了一次文件来解析查询,所以理想情况下我应该有7000个查询,但我看到大约有21k个查询正在编写中。为什么会这样?解决办法是什么?

变量k和l具有预期的相同值k = l = 7000

我正在使用try-except来绕过TypeError: argument of type 'NoneType' is not iterable异常。

我对您的数据格式一无所知,但我在使用html.unescape解析自己的一些JSON文件时遇到了这个问题,由于某种原因,我的JSON中有空字符串,当运行json库时,这些空字符串被转换为None对象。

您需要在代码中添加一个检查,以确保您试图解析的对象不是None。

以下是我在代码中的操作方式:

message_body = chat['Text']
# Convert symbols like '&#39' into the actual character representation
if (message_body is not None):
message_body = html.unescape(message_body)

最新更新