【问题标题】:Python removing a non alphabetical character/words from a list with a special casesPython从具有特殊情况的列表中删除非字母字符/单词
【发布时间】:2021-03-22 14:24:00
【问题描述】:

大家好,我只是想知道如果列表中的单词不包含任何字母字符,我该如何保留要删除的单词,但如果它包含任何字母字符后跟任何类型的特殊字符或数字,则不会被删除

假设我有一个句子/单词列表,如下所示:

['python','abc123','@@','!!','12345abc#','hello@','141351351','123abc']

所需的输出将是:

['python','abc123','','','12345abc#','hello@','','123abc']

我尝试过的如下:

data = ['python','abc123','@@','!!','12345abc#','hello@','141351351','123abc']
regex = re.compile('[^a-zA-Z0-9&._-]')
filtered= [regex.sub('', each_data) for each_data in data ]

这会导致:

['python', 'abc123', '12345abc', 'hello', '141351351', '123abc']

删除所有错误的特殊字符我不知道如何解决这个问题,我仍在考虑如何使用正则表达式解决它,我也尝试过使用 nltk,但似乎找不到答案任何一个。任何形式的提示或帮助将不胜感激

【问题讨论】:

  • 如果您需要更多帮助,请发表评论。

标签: python regex


【解决方案1】:

我不确定我是否理解您的问题,但您提供的示例输入输出可以处理为:

[item if re.search('(?i)[a-z]', item) else '' for item in your_list]

你的例子:

your_list = ['python','abc123','@@','!!','12345abc#','hello@','141351351','123abc']

import re
[item if re.search('(?i)[a-z]', item) else '' for item in your_list]

# output:
# ['python', 'abc123', '', '', '12345abc#', 'hello@', '', '123abc']

【讨论】:

    【解决方案2】:

    您可以使用过滤掉列表中不包含字母的任何项目

    ["" if not any(c.isalpha() for c in x) else x for x in l]
    

    使用re库,你可以使用[^\W\d_]match any Unicode letter(或[A-Za-z]只处理ASCII字母)这样的模式,你可以使用

    import re
    print( ["" if not re.search(r'[^\W\d_]', x) else x for x in  l] )
    

    但是,非正则表达式方法似乎已经适合您了。

    注意:“任何字母字符后跟任何类型的特殊字符或数字”可以与 [^\W\d_][\W\d_][A-Za-z][^A-Za-z] 仅用于 ASCII)模式匹配, 一个字母后跟一个非字母。

    Python demo

    import re
    l = ['python','abc123','@@','!!','12345abc#','hello@','141351351','123abc']
    print( ["" if not re.search(r'[^\W\d_]', x) else x for x in  l] )
    # => ['python', 'abc123', '', '', '12345abc#', 'hello@', '', '123abc']
    print( ["" if not any(c.isalpha() for c in x) else x for x in  l] )
    # => ['python', 'abc123', '', '', '12345abc#', 'hello@', '', '123abc']
    

    【讨论】:

      猜你喜欢
      • 2018-11-29
      • 1970-01-01
      • 1970-01-01
      • 2012-05-30
      • 2017-04-17
      • 1970-01-01
      • 2014-04-26
      • 2019-11-21
      • 1970-01-01
      相关资源
      最近更新 更多