【问题标题】:Conditionally replace text in a json dataset有条件地替换 json 数据集中的文本
【发布时间】:2022-06-22 23:34:58
【问题描述】:

我有一个如下格式的 json 文件:

data = [
        {"url": "example1.com", "text": ["\"Incomplete quote 1 \u00a0", "\"Complete quote 1\""]},
        {"url": "example1.com", "text": ["\"Incomplete quote 2 \u00a0", "\"Complete quote 2\""]},
        ]

我想有条件地替换数据集文本部分的字符串中的某些字符。这是我想要对单个字符串执行的操作的示例:

text = "\"Incomplete quote 1 \u00a0"

if len(re.findall(r'\"', text))==1:
    text = text.replace(" \u00a0", "\"")

print(text)

# "Incomplete quote 1" 

现在,我想对数据集中每一行中的每个字符串执行相同的操作(对于“文本”)。所需的输出是:

data = [
        {"url": "example1.com", "text": ["\"Incomplete quote 1\"", "\"Complete quote 1\""]},
        {"url": "example1.com", "text": ["\"Incomplete quote 2\"", "\"Complete quote 2\""]},
        ]

【问题讨论】:

    标签: json loops replace


    【解决方案1】:

    这行得通:

    for item in data:
        item['text'] = [sub.replace('\u00a0', '\" \u00a0') 
                       if len(re.findall(r'\"', sub))==1
                       else sub
                       for sub in item['text']]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-29
      • 2020-03-14
      • 2020-03-24
      • 1970-01-01
      相关资源
      最近更新 更多