我正在尝试编写一个Python解析器来修改方括号内的文本 例如如果文本文件包含
TypeError: __call__() got multiple values for argument 'block'
答案 0 :(得分:0)
fileinput.input
将用于就地文件编辑re.match
和match.group
将用于捕获括号内的文字这是代码(我已将评论内联):
def modify_text_inside_brackets(file_name, tag):
with fileinput.input(files=(file_name), inplace=True) as text_file:
for line in text_file:
# split the line into groups
matches = re.match(r"(.*)(\[.*\])(.*)", line)
if matches:
# get the text inside the brackets
# group(0): the entire matching line
# group(1): everything before the opening [
# group(2): [ .. ]
# group(3): everything after the closing ]
text_inside_brackets = matches.group(2)[1:-1]
# create a new [..] string with the prepended tag
modified_text = "[{},{}]".format(tag, text_inside_brackets.strip())
# replace the original [..] with the modified [..]
modified_line = line.replace(matches.group(2), modified_text)
# print out the modified line to the file
print(modified_line, end="")
else:
print(line, end="")
modify_text_inside_brackets("input.txt", "TAG")
鉴于此“input.txt”:
[ 123,456]
[ city is beautiful]
This text has no brackets and should be unchanged.
It can also [ handle lines with inline] brackets.
代码会像这样修改它:
[TAG,123,456]
[TAG,city is beautiful]
This text has no brackets and should be unchanged.
It can also [TAG,handle lines with inline] brackets.
注意: