python - 仅从 JSON 文件中删除引号内的标点符号

标签 python json python-2.7

我有多个 JSON 文件,其中包含最多可达数百行的字符串。我的文件示例中只有三行,但这些“短语”平均约有 200-500 个:

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

我需要一个脚本进入文件(我们可以称之为 ExampleData.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 还是个新手,必须马上做一些非常重要的事情,但这并不是我的选择。

最佳答案

这应该有效。

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 作为字符串加载。然后使用正则表达式查找双引号之间的所有子字符串。替换/删除所有这些子字符串中的标点符号,然后写回文件:

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)

关于python - 仅从 JSON 文件中删除引号内的标点符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58733756/

相关文章:

python - 我们如何合并两个数据框而不丢失Python中的任何行

javascript - 如何安全地使用 JSON.stringify

python - django 中的命名约定是强制性的吗?

python-2.7 - 理解python 2.7和3.5+中的struct.pack

python - python中最快的递归FFT

python - 使用 uvicorn + fastapi 在 AWS EC2 上出现 uvicorn 错误

python - 从 python 运行 bash 脚本

python - 用lxml解析html(标签h3)

php - PHP如何访问特定的json数据

python - requests.get 一直卡在 Twitter Api(Python 请求库)上