【发布时间】:2019-11-06 15:39:51
【问题描述】:
我有多个 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 还是这么陌生,必须马上做一些不平凡的事情,但这不是我的选择。
【问题讨论】:
-
尝试将您的 json 加载为 dict,然后使用
re.sub或str.translate处理您的字符串以删除不需要的字符,正如此答案所建议的 (stackoverflow.com/a/3939381/8053370),然后将其再次保存到您的文件中。 -
我已经能够以我的方式通过大部分逻辑。我将
open(.json 文件作为fin并将data = fin.read()data = data.replace('?','')应用于我所有适用的字符,逗号除外。剩下的就是弄清楚如何确定逗号是否在双引号内。我能想到的方法是:如果逗号在\n旁边,如果它在双引号旁边,或者如果它位于两个引号内。仍然不知道其中一条或另一条路线是否是更好的选择。
标签: python json python-2.7