【问题标题】:Regular expression to skip some specific characters跳过某些特定字符的正则表达式
【发布时间】:2017-07-24 07:50:34
【问题描述】:

我正在尝试清理字符串,使其没有任何标点符号或数字,它必须只有 a-z 和 A-Z。 例如,给定 String 为:

"coMPuter scien_tist-s are,,,  the  rock__stars of tomorrow_ <cool>  ????"

需要的输出是:

['computer', 'scientists', 'are', 'the', 'rockstars', 'of', 'tomorrow']

我的解决办法是

re.findall(r"([A-Za-z]+)" ,string)

我的输出是

['coMPuter', 'scien', 'tist', 's', 'are', 'the', 'rock', 'stars', 'of', 'tomorrow', 'cool']

【问题讨论】:

  • 您最好的解决方案是使用简单的替换来删除所有不是 a-z 和空格的字符。 [^A-Za-z ]+(你可以用\s代替右括号后面的空格,然后用空格作为分隔符对字符串进行拆分。在正则表达式中,你可以
  • 您能详细说明一下吗?
  • @cfqueryparam 谢谢你在说什么 re.sub( r'([^a-zA-Z\s]+)', '', s).split()

标签: python regex string python-2.7


【解决方案1】:

你不需要使用正则表达式:

(如果要所有小写单词,则将字符串转换为小写),拆分单词,然后过滤掉以字母开头的单词:

>>> s = "coMPuter scien_tist-s are,,,  the  rock__stars of tomorrow_ <cool>  ????"
>>> [filter(str.isalpha, word) for word in s.lower().split() if word[0].isalpha()]
['computer', 'scientists', 'are', 'the', 'rockstars', 'of', 'tomorrow']

在 Python 3.x 中,filter(str.isalpha, word) 应替换为 ''.join(filter(str.isalpha, word)),因为在 Python 3.x 中,filter 返回一个过滤器对象。

【讨论】:

  • 谢谢它对我有用....你能告诉我正则表达式更省时还是这种循环方法?
  • @RajaHammadFarooq,没有给出正则表达式答案,所以我无法比较。
【解决方案2】:

在所有回答的人的推荐下,我得到了我真正想要的正确解决方案,谢谢大家...

s = "coMPuter scien_tist-s are,,,  the  rock__stars of tomorrow_ <cool>  ????"    
cleaned = re.sub(r'(<.*>|[^a-zA-Z\s]+)', '', s).split()
print cleaned

【讨论】:

  • 如果cool" 包围怎么办? ... tomorrow_ "cool" 是否应该包含在内?
【解决方案3】:

使用re,虽然我不确定这是否是你想要的,因为你说你不想要“酷”的剩菜。

import re

s = "coMPuter scien_tist-s are,,,  the  rock__stars of tomorrow_ <cool>  ????"

REGEX = r'([^a-zA-Z\s]+)'

cleaned = re.sub(REGEX, '', s).split()
# ['coMPuter', 'scientists', 'are', 'the', 'rockstars', 'of', 'tomorrow', 'cool']

编辑

WORD_REGEX = re.compile(r'(?!<?\S+>)(?=\w)(\S+)')
CLEAN_REGEX = re.compile(r'([^a-zA-Z])')

def cleaned(match_obj):
    return re.sub(CLEAN_REGEX, '', match_obj.group(1)).lower()

[cleaned(x) for x in re.finditer(WORD_REGEX, s)]
# ['computer', 'scientists', 'are', 'the', 'rockstars', 'of', 'tomorrow']

WORD_REGEX 对任何单词字符使用正向预读,对 <...> 使用负预读。任何使其通过前瞻的非空白都被分组:

(?!<?\S+>) # negative lookahead
(?=\w) # positive lookahead
(\S+) #group non-whitespace

cleaned 采用匹配组并删除带有CLEAN_REGEX 的任何非单词字符

【讨论】:

  • OP 想要['computer', 'scientists', 'are', 'the', 'rockstars', 'of', 'tomorrow']
  • 是的,这也是一个很好的方法,我也想跳过 括号内的任何文本“”,我该怎么办??
猜你喜欢
  • 2011-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多