繁体   English   中英

如何从句子中删除数字和长度小于 2 的单词?

[英]How can I remove numbers, and words with length below 2, from a sentence?

我正在尝试删除长度低于 2 的单词和任何数字单词。 例如

 s = " This is a test 1212 test2"

所需的输出是

" This is test test2"

我试过\\w{2,}这会删除所有长度小于 2 的单词。当我添加\\D+这会删除所有数字,因为我不想从test2删除 2 。

您可以使用:

s = re.sub(r'\b(?:\d+|\w)\b\s*', '', s)

正则表达式演示

图案详情:

  • \\b : 匹配单词边界
  • (?:\\d+|\\w) : 匹配单个单词字符或 1+ 个数字
  • \\b : 匹配单词边界
  • \\s* : 匹配 0 个或多个空格

您可以使用工作边界'\\b'并删除边界内 1 个字符长的任何内容:数字或字母,无关紧要。 还要删除边界之间的任何只是数字的东西:

import re

s = " This is a test 1212 test2"

print( re.sub(r"\b([^ ]|\d+)\b","",s))

输出:

 This is  test  test2

解释:

\b(           word boundary followed by a group
   [^ ]           anything that is not a space (1 character) 
       |              or
        \d+       any amount of numbers
)             followed by another boundary

re.sub(pattern, replaceBy, source)替换为""

也许(?i)\\b(?:\\d+|[az])\\b[ \\t]*
https://regex101.com/r/bnS15k/1

做一些 wsp 修剪。


对于这类事情,空白修剪可能更重要。
这个修改过的版本从双方做到了。

只需使用
(?im)(?:([ \\t])+\\b(?:\\d+|[az])\\b[ \\t]*[ \\t]*|^\\b(?:\\d+|[az])\\b[ \\t]*[ \\t]*())
用替换\\1\\2

https://regex101.com/r/gSswPe/1
从两侧剥离 wsp。

 (?im)
 (?:
    ( [ \t] )+           # (1)
    \b 
    (?: \d+ | [a-z] )
    \b [ \t]* [ \t]* 
  | 
    ^ \b 
    (?: \d+ | [a-z] )
    \b [ \t]* [ \t]* 
    ( )                  # (2)
 )

你可以这样做:

import re

s = " This is a test 1212 test2"

p = re.compile(r"(\b(\w{0,1})\b)|(\b(\d+)\b)")

result = p.sub('', s)

print(result)

输出:

" This is  test  test2"

我注意到您想要的输出不包含连续的空格。 如果你想用一个替换连续的空格,你可以这样做:

p = re.compile(r"  +")
result = p.sub(' ', result)

输出:

" This is test test2"

(\\b(\\w{0,1})\\b)这个组匹配长度最大为 1 的单词(包括)

(\\b(\\d+)\\b)这个组只匹配由数字组成的单词

| 管道表示“或”,因此该表达式将匹配组 1 或组 2

\\b这是“词边界”。 通过用“\\b”包围一些正则表达式,它将匹配“仅整个单词”

\\w它将匹配应该是单词的一部分的字符

\\d+这意味着“至少一位或更多”

请注意, \\b\\w将匹配什么取决于您使用的正则表达式风格。

只是为了投入我的两分钱 - 你可以使用内置的字符串函数:

s = " This is a test 1212 test2"
result = " ".join(word for word in s.split() 
                  if len(word) >= 2 and not word.isdigit())
print(result)

哪个会产生

This is test test2

暂无
暂无

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

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