【问题标题】:How to concatenate multiple paragraphs from JSON field into one paragraph in .txt?如何将 JSON 字段中的多个段落连接成 .txt 中的一个段落?
【发布时间】:2018-08-11 17:33:37
【问题描述】:

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

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:

{ “评论”:[ { “创建”:“2008-07-09T00:00:00”, "text": "有一些让人放心的东西等等。\n\n乐队的技巧 等等\n\n克雷格·芬恩的歌声等等\n", }, “votes_negative”:0, “votes_positive”:0 } ] }

结果输出(.txt):

有一些令人放心的东西等。

乐队实力等

克雷格·芬恩的歌声等

非常感谢。

【问题讨论】:

  • @usr2564301 我已经提供了一个简化的示例,谢谢。

标签: python json string file dictionary


【解决方案1】:

如果我正确阅读了您的问题,您希望所有内容都集中在一条线上,您可以这样做:

...
            output = item['text'].replace('\n',' ')
...

输出:

There's something reassuring etc.   The band's skill etc.   Craig Finn's vocals etc.

或者如果你想在每个之间有一行:

...
            output = item['text'].replace('\n\n','\n')
...

输出:

There's something reassuring etc.
The band's skill etc.
Craig Finn's vocals etc.
# One extra blank line here

【讨论】:

    【解决方案2】:

    您没有将 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’))
    

    【讨论】:

      猜你喜欢
      • 2020-06-21
      • 2013-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-28
      • 2019-11-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多