【问题标题】:Regex for removing all characters except A-z and deleting all words containing digits用于删除除 A-z 之外的所有字符并删除所有包含数字的单词的正则表达式
【发布时间】:2019-01-21 07:25:53
【问题描述】:

我的目标是编写一个函数来输入文本并将除拉丁字母 (A-z) 以外的所有字符替换为空格,并删除所有包含数字的单词。然后它将所有多个空格替换为一个空格。

例子:

' hello, world! ho1hoho2ho, merry xmas!! ho1ho1 :))' -> 'hello world merry xmas'. 

实现此功能的 Python 函数:

def clean_text(text):
    text_valid = re.sub(u'[^A-z0-9]', ' ', text)
    return ' '.join(word for word in text_valid.split()
                    if not re.search(r'\d', word))

现在我想知道是否有一个单一的正则表达式,也许,所以我可以写一些类似的东西

return ' '.join(re.findall(enter_my_magical_regex_here))

或者,也许还有另一种方法可以用更快(希望更短)的代码替换上面的代码?

【问题讨论】:

  • 该字符集应该是 [^0-9A-Za-z] 以匹配除 ASCII 数字和字母之外的所有内容。 (\W 会让下划线通过。)
  • 不要使用[A-я]匹配俄语字母,需要使用[А-Яа-яёЁ]。英文可以匹配[a-zA-Z]
  • 试试re.sub(ur'^\s*|\s*$|\s*(?:[^\W\d_]*\d[^\W\d_]*|[^A-Za-z\d\s]+)', '', text, flags=re.U)

标签: python regex replace


【解决方案1】:

你可以使用

' '.join(re.sub('([^A-Za-z0-9 ]|[^ ]*[0-9][^ ]*)', '', text).split())

【讨论】:

  • u有什么用?
【解决方案2】:

这将为您提供所需的输出 -

x = ' hello, world! ho1hoho2ho, merry xmas!! ho1ho1 :))'
re.sub('[!,]', '', ' '.join([i for i in x.split() if not re.findall('[\d+:\\?\"<>*/|]', i)]))

但是你可能不得不在这里和那里调整一些东西

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-03
    • 1970-01-01
    • 2011-09-08
    • 1970-01-01
    • 1970-01-01
    • 2014-01-10
    • 1970-01-01
    相关资源
    最近更新 更多