【问题标题】:regex: how to combine two exact match into one using re.sub() in python?正则表达式:如何在 python 中使用 re.sub() 将两个完全匹配组合成一个?
【发布时间】:2020-07-20 17:07:28
【问题描述】:

我想将两行代码合二为一。

第一个是删除所有string.punctuations。我使用的代码如下:

df[col].apply(lambda x: re.sub(r'[!\"#$%&\'()*+,-.\/:;<=>?@[\\]^_`{|}~]+', '', x))

第二个是去掉一些特殊字符(我不知道如何表达这种像“’‘”这样的双引号;这些和普通的'""'引号不同):

df[col].apply(lambda x: re.sub(r'[“’‘”]', '', x))

我想在一行代码中将它们全部删除。我试图简单地将第二个完全匹配添加到第一个,但事实证明第二个匹配没有在文本中删除。我想知道为什么以及如何有效地删除那些punctuations

需要清理的示例文本可能是:

text = '“Client” refers to Client or “”any User uploads or otherwise supplies to, or stores in, the Services under Client’s account.'

【问题讨论】:

标签: python regex replace


【解决方案1】:

根据您的回复,我相信这就是您正在寻找的答案:

import re
text = '“Client” refers to Client or “”any User uploads or otherwise supplies to, or stores in, the Services under Client’s account.'
re.sub(r'[^\w|^\d|^\s]+', '', text)

输出:

'Client refers to Client or any User uploads or otherwise supplies to or stores in the Services under Clients account'

替换所有字符,除了:

  • ^\w 单词字符,例如 A-Z 和 a-z
  • ^\d 位数
  • ^\s空格

考虑到您的特殊字符列表的广度,这种排他过滤比包含过滤更有效。

【讨论】:

  • 谢谢,但我试过了,它不适用于示例文本。无法删除第二个匹配项@rgk
  • 在这种情况下,我认为 Sushanth 对您的问题的评论更接近您的解决方案 - 删除所有非单词和非数字字符,但您还需要为空格添加 ^\s。查看我的更新答案
猜你喜欢
  • 2015-08-18
  • 1970-01-01
  • 1970-01-01
  • 2017-12-27
  • 2023-03-19
  • 1970-01-01
  • 1970-01-01
  • 2022-11-29
  • 1970-01-01
相关资源
最近更新 更多