使用Python删除小词

Tho*_*mas 19 python regex

是否可以使用正则表达式删除文本中的小词?例如,我有以下字符串(文本):

anytext = " in the echo chamber from Ontario duo "
Run Code Online (Sandbox Code Playgroud)

我想删除3个字符或更少的所有单词.结果应该是:

"echo chamber from Ontario"
Run Code Online (Sandbox Code Playgroud)

是否可以使用正则表达式或任何其他python函数?

谢谢.

mgi*_*son 43

无论如何,我认为你不需要这个简单例子的正则表达式...

' '.join(word for word in anytext.split() if len(word)>3)
Run Code Online (Sandbox Code Playgroud)


Mar*_*ers 30

当然,它也不是那么难:

shortword = re.compile(r'\W*\b\w{1,3}\b')
Run Code Online (Sandbox Code Playgroud)

上面的表达式选择任何前面有一些非单词字符(基本上是空格或开头)的单词,短于1到3个字符,并以单词边界结束.

>>> shortword.sub('', anytext)
' echo chamber from Ontario '
Run Code Online (Sandbox Code Playgroud)

\b边界的比赛是很重要的位置,他们保证你不匹配只是一个字的第一个或最后3个字符.

\W*一开始,您可以删除这两个词和前面的非单词字符,这样句子的其余部分仍然匹配起来.需要注意的是标点符号包括在\W使用\s,如果你只是想删除前面的空白.

对于它的价值,这个正则表达式解决方案在其余单词之间保留了额外的空白,而mgilson的版本将多个空白字符折叠成一个空格.不确定这对你是否重要.

他的列表理解解决方案两者中更快的:

>>> import timeit
>>> def re_remove(text): return shortword.sub('', text)
... 
>>> def lc_remove(text): return ' '.join(word for word in text.split() if len(word)>3)
... 
>>> timeit.timeit('remove(" in the echo chamber from Ontario duo ")', 'from __main__ import re_remove as remove')
7.0774190425872803
>>> timeit.timeit('remove(" in the echo chamber from Ontario duo ")', 'from __main__ import lc_remove as remove')
6.4250049591064453
Run Code Online (Sandbox Code Playgroud)

  • 特别是因为OP中的第一行是:"是否有可能使用***正则表达式***删除......"正义+1 (2认同)