【发布时间】:2018-07-15 10:58:52
【问题描述】:
我正在尝试使用 python 替换跨越多行文本文件的文本块。这是我的输入文件的样子。
输入.txt:
ABCD abcd (
. X (x),
.Y (y)
);
ABCD1 abcd1 (
. X1 (x1),
.Y1 (y1)
);
我正在阅读带有以下代码的上述文件并尝试替换文本但未能这样做。下面是我的代码。
fo = open(input.txt, 'r')
input_str = fo.read()
find_str = '''ABCD abcd (
.X (x),
.Y (y)
);'''
replace_str = '''ABCDE abcde (
. XX (xx),
.YY (yy)
);'''
input_str = re.sub(find_str, replace_str, input_str)
但是 input_str 似乎没有改变。不知道我错过了什么。有什么线索吗?
【问题讨论】:
-
如果您替换文字字符串,为什么要使用正则表达式?使用
input_str = input_str.replace(find_str, replace_str) -
代码在字符串中包含缩进,但您问题中的示例数据未缩进。如果这被正确转录,则正则表达式根本不匹配。
-
@Wiktor Stribiżew:我也尝试过替换。但不幸的是,它也没有用。
-
您使用的是 re 还是 regex 模块?见https://pypi.org/project/regex/
-
确保替换完全相同的字符串,计算所有空格等。它会起作用。
标签: python regex string python-3.x