python - 删除具有特殊字符 "\"和 "/"的单词

标签 python regex special-characters

在推文分析过程中,我在包含\或/的“词”中运行(在一个“词”中可能出现不止一次)。我想完全删除这些词,但不能完全确定这一点

这是我尝试过的:

sen = 'this is \re\store and b\\fre'
sen1 = 'this i\s /re/store and b//fre/'

slash_back =  r'(?:[\w_]+\\[\w_]+)'
slash_fwd = r'(?:[\w_]+/+[\w_]+)'
slash_all = r'(?<!\S)[a-z-]+(?=[,.!?:;]?(?!\S))'

strt = re.sub(slash_back,"",sen)
strt1 = re.sub(slash_fwd,"",sen1)
strt2 = re.sub(slash_all,"",sen1)
print strt
print strt1
print strt2

我想得到:

this is and
this i\s and
this and

但是,我收到:

and 
this i\s / and /
i\s /re/store  b//fre/

补充:在这种情况下,“单词”是一个由空格或标点符号分隔的字符串(如常规文本)

最佳答案

这个怎么样?我添加了一些标点示例:

import re

sen = r'this is \re\store and b\\fre'
sen1 = r'this i\s /re/store and b//fre/'
sen2 = r'this is \re\store, and b\\fre!'
sen3 = r'this i\s /re/store, and b//fre/!'

slash_back =  r'\s*(?:[\w_]*\\(?:[\w_]*\\)*[\w_]*)'
slash_fwd = r'\s*(?:[\w_]*/(?:[\w_]*/)*[\w_]*)'
slash_all = r'\s*(?:[\w_]*[/\\](?:[\w_]*[/\\])*[\w_]*)'

strt = re.sub(slash_back,"",sen)
strt1 = re.sub(slash_fwd,"",sen1)
strt2 = re.sub(slash_all,"",sen1)
strt3 = re.sub(slash_back,"",sen2)
strt4 = re.sub(slash_fwd,"",sen3)
strt5 = re.sub(slash_all,"",sen3)
print(strt)
print(strt1)
print(strt2)
print(strt3)
print(strt4)
print(strt5)

输出:

this is and
this i\s and
this and
this is, and!
this i\s, and!
this, and!

关于python - 删除具有特殊字符 "\"和 "/"的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33470048/

相关文章:

java - 如何匹配引号和数字之间的文本

.net - 保留转义字符的新 Uri

keyboard - 是否有一种编程语言使用(非扩展)ascii 表中的字符以外的字符?

python - 使用多处理时无法重现 scikit-learn 和 numpy 相关代码

c# - 正则表达式替换多个新行

python - 如何计算仅给出负面信息的可能连接组件的最小数量

regex - 如何在 Perl 替换中替换匹配项之前的所有文本?

parameters - GET 参数中允许的字符

python - Numpy中的线段相交算法

python - Pandas突然无法打开Excel文件(在OLE2复合文档中找不到工作簿