繁体   English   中英

使用正则表达式删除重复的特殊字符(如果单独存在,但在被单词或数字包围时不存在)

[英]Remove repeating special characters using regular expression if present alone but not when surrounded by words or numbers

如何从作为个体存在的字符串 IFF 中删除特殊字符。 我正在尝试研究推文作者分类模型,我的想法是有些人使用特殊字符作为商标,它可以帮助建模更好的判断,例如

P!nk
A$AP

是两位歌手的商标。 我想删除单个和重复的特殊字符,例如

whatt??
This is Good. I want both dots removed.
I'm thinking....

但不想删除#hashtag_for_life或类似的东西

我用过了

re.sub(r'([\W_])\1+',' ','hi my % na$me is @shady #for_life')

但个人失败。 有人可以提供解决方案。

编辑:示例

我该如何转换

'p!nk & A$AP are 2 singers..... what? are the b0th rappers? ? ? NO!! #singer ##rapper @shady'

'p!nk A$AP are singers what are the b0th rappers NO #singer #rapper @shady'

这意味着个别数字消失了,个别特殊字符消失了,尾随特殊字符消失了,重复的特殊字符被更改为位于单词中间或开头的单个特殊字符。

请您尝试以下操作:

import re
str = 'p!nk & A$AP are 2 singers..... what? are the b0th rappers? ? ? NO!! #singer ##rapper @shady'

str = re.sub(r'(?<=\s)[\W\d](?=(\s|$))', '', str)
str = re.sub(r'(?<=\w)\W+(?=(\s|$))', '', str)
str = re.sub(r'(\W)\1+(?=\w)', r'\1', str)

print(str)

输出:

p!nk A$AP are singers what are the b0th rappers NO #singer #rapper @shady
  • (?<=\\s)[\\W\\d](?=(\\s|$))匹配由空格包围或在行尾的单个非字母或数字字符。
  • (?<=\\w)\\W+(?=(\\s|$))匹配单词后的单个非字母字符。
  • (\\W)\\1+(?=\\w)匹配单词前面的两个或多个连续的非字母字符。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM