gpt4 book ai didi

python - 如何将 JSON 字段中的多个段落连接成 .txt 中的一个段落?

转载 作者:行者123 更新时间:2023-11-28 17:08:53 26 4
gpt4 key购买 nike

我正在尝试将来自多个段落的评论连接成一个——我正在尝试这样做:

for x in docs:
with open(fp) as data_file:
data_item = json.load(data_file)
b = data_item['reviews']
for item in b:
name = '000' + str(counter) + '.txt'
file = open(name, 'wb')
output = item['text']
" ".join(output.split())
counter = counter+1
file.write(output.encode('utf-8'))
file.close()

但是它不起作用;每个 .txt 输出文件在 JSON 字段中都是原样(带有\n\n)...

示例 JSON:

{ "reviews": [ { "created": "2008-07-09T00:00:00", "text": "There's something reassuring etc. \n\nThe band's skill etc. \n\nCraig Finn's vocals etc.\n", }, "votes_negative": 0, "votes_positive": 0 } ] }

结果输出(.txt):

There's something reassuring etc.

The band's skill etc.

Craig Finn's vocals etc.

非常感谢。

最佳答案

您不将 join 的输出分配给变量,试试这个:

# sidenote: use enumerate to replace counter
for counter, item in enumerate(b):
name = '000' + str(counter) + '.txt'
output = item['text']
output = ' '.join(output.split())

# imho with is always nicer than open/close
with open(name, ‘wb’) as file:
file.write(output.encode(‘utf-8’))

关于python - 如何将 JSON 字段中的多个段落连接成 .txt 中的一个段落?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49087139/

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