【问题标题】:How can I remove numbers, and words with length below 2, from a sentence?如何从句子中删除数字和长度低于 2 的单词?
【发布时间】:2020-10-14 18:00:10
【问题描述】:

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

 s = " This is a test 1212 test2"

想要的输出是

" This is test test2"

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

【问题讨论】:

  • @P....这不会删除 1212。​​应该删除它,因为它是一个数字。我能够通过 \w{2,} 删除所有不超过 2 个单词的单词
  • 什么是“词”?
  • @Maxt8r,单词是字母字符或可能包含数字字符的字母字符。比如测试。 test1, tes2 是单词,而 1 , 2, 0.2 0.4 不是单词
  • 2 个字母的要求是连续的还是在“单词”内?
  • 非正则表达式解决方案:" ".join([x for x in s.split() if not x.isdigit() and not (x == x[0] and x.isalpha())]) (demo)。只有尾随/前导空格会被删除。

标签: python regex


【解决方案1】:

你可以使用:

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

RegEx Demo

模式详情:

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

【讨论】:

  • 将顺序更改为\d+|\w 可防止不必要的回溯。
  • 非常好的点@ctwheels 我肯定错过了这个
【解决方案2】:

您可以利用工作边界'\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)替换为""

【讨论】:

  • 将顺序改为\d+|[^ ] 可以防止不必要的回溯。
【解决方案3】:

你可以这样做:

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 它将匹配应该是单词一部分的 wharacters

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

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

【讨论】:

  • {0,1} 可以替换为 ? - 更短更简洁。此外,更改顺序可以防止不必要的回溯。
【解决方案4】:

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

做一些 wsp 修剪。


空白修剪对于这类事情可能更重要。
这个修改后的版本从两个方面都做到了。

只需使用
(?im)(?:([ \t])+\b(?:\d+|[a-z])\b[ \t]*[ \t]*|^\b(?:\d+|[a-z])\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)
 )

【讨论】:

    【解决方案5】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-02
      • 1970-01-01
      • 2017-11-03
      • 1970-01-01
      • 2014-10-06
      • 2021-10-27
      • 2021-08-20
      • 1970-01-01
      相关资源
      最近更新 更多