首页 > 解决方案 > 如何为 .isalnum() 设置异常?

问题描述

我正在尝试通过使用 .isalnum() 函数循环遍历单词中的每个字符来从列表中的字符串中删除不需要的特殊符号,并且我使用条件为情况下的撇号符号设置异常,例如“不能”、“没有”、“不会”。但它也为我不需要的情况保留了这个符号,比如“'”、“'cant”、“'hello'”。有没有办法只在符号位于单词中间时保留?

data_set = "Hello WOrld &()*hello world ////dog /// cat world hello can't "

split_it = data_set.lower().split()
new_word = ''
new_list = list()
for word in split_it:
    new_word = ''.join([x for x in word if x.isalnum() or x == " ' "])
    new_list.append(new_word)

print(new_list)

['你好','世界','你好','世界','狗','','猫','世界','你好',“不能”]

标签: pythonpython-3.x

解决方案


如果您知道所有不需要的字符,则可以使用.strip()仅从开头和结尾删除它们:

>>> words = "Hello WOrld &()*hello world ////dog /// cat world hello can't ".lower().split()
>>> cleaned_words = [word.strip("&()*/") for word in words]
>>> print(cleaned_words)
['hello', 'world', 'hello', 'world', 'dog', '', 'cat', 'world', 'hello', "can't"]

否则,您可能需要一个匹配除白名单之外的任何字符的正则表达式,锚定到字符串的开头或结尾,然后用于re.sub()删除它们:

>>> import re
>>> nonalnum_at_edge_re = re.compile(r'^[^a-z0-9]+|[^a-z0-9]+$', re.I)
>>> cleaned_words = [re.sub(nonalnum_at_edge_re, '', word) for word in words]
['hello', 'world', 'hello', 'world', 'dog', '', 'cat', 'world', 'hello', "can't"]

推荐阅读