Python Regex re.sub无法取代

时间:2019-05-13 19:26:55

标签: python regex python-3.x

我正在尝试修改此文件,但是re.sub并未修改原始文件

我的代码如下

import sys
import re
import json
from collections import OrderedDict

inputjson = sys.argv[1]

with open(inputjson, 'r') as fid:
        jsondata = json.load(fid, object_pairs_hook=OrderedDict)

for i in range(len(jsondata['value']['segments'])):
        trans = jsondata['value']['segments'][i]['transcriptionData']['content']
        if re.search(r'^ *\[[^\[\]]*\] *$', trans):
                continue
        else:
                while re.search(r'\[(lang[^\[\]]*)\]',  trans):
                        re.sub(r'\[(lang[^\[\]]*)\]', r'<\1>', trans)
                while re.search(r'\[/(lang[^\[\]]*)\]',  trans):
                        re.sub(r'\[/(lang[^\[\]]*)\]', r'</\1>', trans)

最后,我试图修改inputjson,但是在运行代码后打开文件时,没有任何改变。请让我知道我在做什么错。谢谢!

0 个答案:

没有答案