从JSON文件中删除Puncuation,只在引号内

2024-04-25 22:08:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我有多个JSON文件,其中填充的字符串最多可以达到几百行。在我的文件示例中,只有三行,但平均来说,这些“短语”大约有200-500行:

{
   "version": 1,
   "data": {
       "phrases":[
           "A few words that's it.",
           "This one, has a comma in it!",
           "hyphenated-sentence example"
        ]
   }
}

我需要有一个脚本进入文件(我们可以称之为示例数据.json)并从文件中删除所有标点符号(特别是这些字符:,.?!'-),而不删除双引号外的,。基本上是这样的:

"A few words that's it.",
"This one, has a comma in it!",
"hyphenated-sentence example."

变成这样:

"A few words that's it",
"This one has a comma in it",
"hyphenated sentence example"

还要注意,除了连字符外,所有标点符号都是如何删除的。用空格代替。


我发现了一个几乎完全相同的问题,但是对于csv文件here,却无法将csv版本转换为可以与JSON一起使用的版本。

我用python得到的最接近的结果是通过另一个线程上的someone else's answer使用一个字符串。你知道吗

input_str = 'please, remove all the commas between quotes,"like in here, here, here!"'

quotes = False

def noCommas(string):
    quotes = False
    output = ''
    for char in string:
        if char == '"':
            quotes = True
        if quotes == False:
            output += char
        if char != ',' and quotes == True:
            output += char
    return output

print noCommas(input_str)

(对不起,我不知道如何在引号中插入代码块)
但它一次只对一个字符有效。但是添加任何额外的规则会导致引号外的文本自身翻倍(请变成pplleeaassee)。
最后一件事是,我必须在python2.7.5中完成这项工作,从我收集的搜索结果来看,这使得这项工作更加困难。
很抱歉,我还是python的新手,必须马上做一些非常重要的事情,但这并不是我的选择。你知道吗


Tags: 文件inoutputthathereitthisone
1条回答
网友
1楼 · 发布于 2024-04-25 22:08:46

这应该管用。你知道吗

import re
import json

with open('C:/test/data.json') as json_file:
    data = json.load(json_file)



for idx, v in enumerate(data['data']['phrases']):
    data['data']['phrases'][idx] = re.sub(r'-',' ',data['data']['phrases'][idx])
    data['data']['phrases'][idx] = re.sub(r'[^\w\s]','',data['data']['phrases'][idx])


with open('C:/test/data.json', 'w') as outfile:
    json.dump(data, outfile,  indent=4)

选项2:

以字符串形式加载json。然后使用regex查找双引号之间的所有子字符串。替换/删除所有子字符串中的标点符号,然后写回文件:

import re
import json
import string




with open('C:/test/data.json') as json_file:
    data = json.load(json_file)

data = json.dumps(data)

strings = re.findall(r'"([^"]*)"', data)

for each in strings:
    new_str =  re.sub(r'-',' ', each)
    new_str = new_str.strip(string.punctuation)
    new_str =  re.sub(r',','', new_str)

    data = data.replace('"%s"' %each, '"%s"' %new_str)


with open('C:/test/data_output.json', 'w') as outfile:
    json.dump(json.loads(data), outfile,  indent=4)

相关问题 更多 >