【问题标题】:remove all the special chars from a list [duplicate]从列表中删除所有特殊字符[重复]
【发布时间】:2022-01-20 12:48:28
【问题描述】:

我有一个字符串列表,其中一些字符串是特殊字符,在结果列表中排除它们的方法是什么

list = ['ben','kenny',',','=','Sean',100,'tag242']

expected output = ['ben','kenny','Sean',100,'tag242']

请指导我实现相同的方法。谢谢

【问题讨论】:

标签: python python-3.x list


【解决方案1】:

字符串模块有一个标点符号列表,您可以使用这些标点符号并从单词列表中排除:

import string

punctuations = list(string.punctuation)

input_list = ['ben','kenny',',','=','Sean',100,'tag242']
output = [x for x in input_list if x not in punctuations]

print(output)

输出:

['ben', 'kenny', 'Sean', 100, 'tag242']

此标点符号列表包括以下字符:

['!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~']

【讨论】:

    【解决方案2】:

    这可以简单地使用 isalnum() 字符串函数来完成。 isalnum() 如果字符串只包含数字或字母,则返回 true,如果字符串包含除此之外的任何特殊字符,则该函数将返回 false。 (isalnum() 不需要导入任何模块,这是一个默认函数)

    代码:

    list = ['ben','kenny',',','=','Sean',100,'tag242']
    olist = []
    for a in list:
       if str(a).isalnum():
          olist.append(a)
    print(olist)
    

    输出:

    ['ben', 'kenny', 'Sean', 100, 'tag242']
    

    【讨论】:

      【解决方案3】:
      my_list = ['ben', 'kenny', ',' ,'=' ,'Sean', 100, 'tag242']
      stop_words = [',', '=']
      
      filtered_output = [i for i in my_list if i not in stop_words]
      

      如果您需要删除其他字符,可以扩展带有停用词的列表。

      【讨论】:

        猜你喜欢
        • 2012-12-16
        • 2012-12-30
        • 1970-01-01
        • 1970-01-01
        • 2019-08-13
        • 2014-05-14
        • 2021-07-27
        • 1970-01-01
        • 2022-01-25
        相关资源
        最近更新 更多