如何在Python中删除两个分隔符之间的文本



我正在尝试删除短语"后面[]括号之间的所有文本;分段":"有关上下文,请参阅文件中的以下片段。

"annotations": [
{
"id": 1,
"image_id": 1,
"segmentation": [
[
621.63,
1085.67,
621.63,
1344.71,
841.66,
1344.71,
841.66,
1085.67
]
],
"iscrowd": 0,
"bbox": [
621.63,
1085.67,
220.02999999999997,
259.03999999999996
],
"area": 56996,
"category_id": 1124044
},
{
"id": 2,
"image_id": 1,
"segmentation": [
[
887.62,
1355.7,
887.62,
1615.54,
1114.64,
1615.54,
1114.64,
1355.7
]
],
"iscrowd": 0,
"bbox": [
887.62,
1355.7,
227.0200000000001,
259.8399999999999
],
"area": 58988,
"category_id": 1124044
},
{
"id": 3,
"image_id": 1,
"segmentation": [
[
1157.61,
1411.84,
1157.61,
1661.63,
1404.89,
1661.63,
1404.89,
1411.84
]
],
"iscrowd": 0,
"bbox": [
1157.61,
1411.84,
247.2800000000002,
249.7900000000002
],
"area": 61768,
"category_id": 1124044
},
........... and so on.....

我最终只想在分词出现后删除方括号之间的所有文本。换句话说,输出看起来像(第一个例子(:

"annotations": [
{
"id": 1,
"image_id": 1,
"segmentation": [],
"iscrowd": 0,
"bbox": [
621.63,
1085.67,
220.02999999999997,
259.03999999999996
],
"area": 56996,
"category_id": 1124044
},

我试过使用下面的代码,但目前运气不太好。我是不是因为新线路出了什么问题?

import re
f = open('samplfile.json')
text = f.read()
f.close()
clean = re.sub('"segmentation":(.*)]', '', text)
print(clean)
f = open('cleanedfile.json', 'w')
f.write(clean)
f.close()

我很感激我在干净的行中对%s的确切定位可能不太正确,但这段代码目前没有删除任何内容。

Python有一个内置的json模块,用于解析和修改JSON。正则表达式可能是脆弱的,并且比它可能的价值更令人头疼。

您可以执行以下操作:

import json
with open('samplfile.json') as input_file, open('output.json', 'w') as output_file:
data = json.load(input_file)
for i in range(len(data['annotations'])):
data['annotations'][i]['segmentation'] = []
json.dump(data, output_file, indent=4)

然后,output.json包含:

{
"annotations": [
{
"id": 1,
"image_id": 1,
"segmentation": [],
"iscrowd": 0,
"bbox": [
621.63,
1085.67,
220.02999999999997,
259.03999999999996
],
"area": 56996,
"category_id": 1124044
},
{
"id": 2,
"image_id": 1,
"segmentation": [],
"iscrowd": 0,
"bbox": [
887.62,
1355.7,
227.0200000000001,
259.8399999999999
],
"area": 58988,
"category_id": 1124044
},
{
"id": 3,
"image_id": 1,
"segmentation": [],
"iscrowd": 0,
"bbox": [
1157.61,
1411.84,
247.2800000000002,
249.7900000000002
],
"area": 61768,
"category_id": 1124044
}
]
}

您的方法基本上是正确的,但Python Regex不接受n作为.,要修复它,请在re((中添加flags=re.DOTALL作为参数。

顺便说一句,您可能需要在regex中使用"而不是"

相关内容

  • 没有找到相关文章

最新更新