Python 使用正则表达式进行多个不同的替换
我正在尝试编写一些Python代码,用正则表达式替换一些不需要的字符串。我写的代码是从这个网站上的另一个问题中提取的 我有一段文字:Python 使用正则表达式进行多个不同的替换,python,regex,Python,Regex,我正在尝试编写一些Python代码,用正则表达式替换一些不需要的字符串。我写的代码是从这个网站上的另一个问题中提取的 我有一段文字: text_1=u'I\u2019m \u2018winning\u2019, I\u2019ve enjoyed none of it. That\u2019s why I\u2019m withdrawing from the market,\u201d wrote Arment.' 我要删除所有\u2019m、\u2019s、\u2019ve等 我编写的代码
text_1=u'I\u2019m \u2018winning\u2019, I\u2019ve enjoyed none of it. That\u2019s why I\u2019m withdrawing from the market,\u201d wrote Arment.'
我要删除所有\u2019m、\u2019s、\u2019ve等
我编写的代码如下所示:
rep={"\n":" ","\n\n":" ","\n\n\n":" ","\n\n\n\n":" ",u"\u201c":"", u"\u201d":"", u"\u2019[a-z]":"", u"\u2013":"", u"\u2018":""}
rep = dict((re.escape(k), v) for k, v in rep.iteritems())
pattern = re.compile("|".join(rep.keys()))
text = pattern.sub(lambda m: rep[re.escape(m.group(0))], text_1)
该代码适用于以下情况:
"u"\u201c":"", u"\u201d":"", u"\u2013":"" and u"\u2018":""
但是,对于以下情况,它并没有起到很好的作用:
u"\u2019[a-z] : The presence of [a-z] turns rep into \\[a\\-z\\] which doesnt match.
我想要的输出是:
如何实现这一点?这里的问题实际上是转义,这段代码更直接地实现了您想要的:
remove = (u"\u201c", u"\u201d", u"\u2019[a-z]?", u"\u2013", u"\u2018")
pattern = re.compile("|".join(remove))
text = pattern.sub("", text_1)
我已经将?
添加到了u2019匹配中,因为我认为这也是给定测试字符串所需要的
为了完整起见,我想我还应该链接到程序包,该程序包实际上可能更接近您试图通过删除这些字符来实现的目的。关于换行符的信息完全改变了答案。为此,我认为使用循环构建表达式实际上比在模式本身中使用更好的格式更不清晰
replacements = {'newlines': ' ',
'deletions': ''}
pattern = re.compile(u'(?P<newlines>\n+)|'
u'(?P<deletions>\u201c|\u201d|\u2019[a-z]?|\u2013|\u2018)')
def lookup(match):
return replacements[match.lastgroup]
text = pattern.sub(lookup, text_1)
replacements={'newlines':'',
“删除”:“”}
模式=重新编译(u'(?P\n+)|'
u'(?P\u201c |\u201d |\u2019[a-z]?|\u2013 |\u2018))
def查找(匹配):
返回替换项[match.lastgroup]
text=pattern.sub(查找,文本1)
最简单的方法是使用以下正则表达式:
X = re.compile(r'((\\)(.*?) ')
text = re.sub(X, ' ', text_1)
你好,谢谢你的回答和链接。然而,有一个小问题。我正在处理的文本文件有许多“\n”,我想替换all(\n为空白)和all(其他不需要的字符串为None)。我已经更新了我帖子中的原始表达,请看一看。此外,我只想扫描文件一次,就可以完成全部工作。@Sam这让问题有了很大的改变,以至于我添加了第二个答案。
X = re.compile(r'((\\)(.*?) ')
text = re.sub(X, ' ', text_1)