如何从字符串中删除单独出现的特殊字符?我正在尝试开发一个推文作者分类模型,我的想法是有些人使用特殊字符作为商标,这可以帮助模型做出更好的判断,例如
P!nkA$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)
匹配在单词前面的两个或多个连续的非字母字符。