Python正则表达式仅根据正则表达式替换段落中的特定行而不是整个文件
Posted
技术标签:
【中文标题】Python正则表达式仅根据正则表达式替换段落中的特定行而不是整个文件【英文标题】:Python regex to replace a Particular line in paragraphs as per regex only not whole file 【发布时间】:2021-09-06 15:58:30 【问题描述】:s="""Paragraph 1
some text blah blah
blah blah
UNWANTED TEXT
some text
Paragraph END
UNWNTED TEXT
Paragraph 2
some text blah blah
blah blah
UNWNTED TEXT
Paragraph END"""
现在 python 代码 re.sub 以仅在段落内替换 UNWANTED TEXT 保留 UNWANTED TEXT 在段落外
search_unwanted_only_inparagrap = re.findall('(?s)(?<=Paragraph)(.*?)(?=END)', text_file, flags = re.MULTILINE )
if search_unwanted_only_inparagrap:
replace_only_insidepara = re.sub(r"UNWANTED TEXT+", " ", text_file) #replace string substitue
print (replace_only_insidepara)
else:
print ("not found")
但是输出替换了文件中所有 UNWANTED TEXT 的实例
Paragraph 1
some text blah blah
blah blah
some text
Paragraph END
Paragraph 2
some text blah blah
blah blah
Paragraph END
但我希望这样
Paragraph 1
some text blah blah
blah blah
some text
Paragraph END
UNWNTED TEXT
Paragraph 2
some text blah blah
blah blah
Paragraph END
请帮忙。
【问题讨论】:
【参考方案1】:您的演示输入应该更“最少”。但是,我试图了解您的要求并尝试了 re.split 作品:
import re
s = """Paragraph 1
some text blah blah
blah blah
UNWANTED TEXT
some text
Paragraph END
UNWANTED TEXT
Paragraph 2
some text blah blah
blah blah
UNWANTED TEXT
Paragraph END"""
reg_para = re.compile(r'(Paragraph\s+\d+.+?END)', re.DOTALL)
paras = reg_para.split(s)
for para in paras:
if reg_para.match(para):
para = re.sub(r"UNWANTED TEXT", " ", para)
# in case you want replace more words:
# of course you can use list of keywords some loops
para = re.sub(r"Another WORD", " ", para)
print(para)
else:
print(para)
输出:
Paragraph 1
some text blah blah
blah blah
some text
Paragraph END
UNWANTED TEXT
Paragraph 2
some text blah blah
blah blah
Paragraph END
【讨论】:
你太棒了。解决了我最近两天一直在苦苦挣扎的问题。非常感谢您宝贵的时间和爱心。 一个额外的查询,我们可以在 re.subremoved = re.sub(r"UNWANTED TEXT", " ", para)
中有多个模式,所有模式只替换空白。喜欢removed = re.sub(r"UNWANTED TEXT", "Another WORD", " ", para)
。我已经为整个文本文件使用了 dict 键值对,但是对于这个正则表达式模式需要一些简单的解决方案。谢谢。以上是关于Python正则表达式仅根据正则表达式替换段落中的特定行而不是整个文件的主要内容,如果未能解决你的问题,请参考以下文章