我试图通过删除字母数字单词(同时包含字母和数字的单词)来清理python3中的一些文本体,但是有一些例外情况我希望保留在文本中。以下代码从文本中删除所有字母数字单词:
import re
string1 = "3n3k game gnma34 xbox360 table"
string2 = "the a22b b3kj3 ps4 2ij2aln potato"
new_string1 = re.sub(r'\w*\d\w*', '', string1)
new_string2 = re.sub(r'\w*\d\w*', '', string2)
上面的代码生成新的字符串1是“游戏表”,新的字符串2是“土豆”。我需要的是新的字符串1是“游戏xbox360表”和新的字符串2是“ps4土豆”。在
我想我可以创建一系列异常,例如:
^{pr2}$但是不太确定如何将这个异常列表合并到正则表达式中(我对这个概念还比较陌生)。任何洞察力都是非常感谢的!在
我找不到正则表达式,但这里有一种方法可以实现它
使用双向方法:拆分并分析单词:
另外,我将正则表达式改为 ^{pr2}$
并尝试在每个“单词”的开头(用
re.match()
)匹配它们,因为\w
也包含数字。在如果能够升级到newer ^{
(*SKIP)(*FAIL)
和更好的表达式,而不需要函数:请参见a demo on regex101.com和完整的
Python
片段:消极使用。一个负的lookahead是zero length:它与任何内容都不匹配;它要么成功,要么失败,并且在完成后,光标仍然在它之前的位置。因此,您需要检查单词边界(
\b
),检查以下文本是否不在异常列表((?!...)
)中,并使用现有的正则表达式匹配单词(\w*\d\w*
)。在要构造lookahead的主体,只需将
exceptions
的元素与其间的|
串联在一起,或者使exceptions
成为一个与您希望直接保留的单词相匹配的regex。在我对Python不太熟悉,下面是示例中regex应该是什么样子的,我希望您可以概括一下:
删除空白
^{pr2}$相关问题 更多 >
编程相关推荐