python - 如何为 .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)
['你好','世界','你好','世界','狗','','猫','世界','你好',“不能”]
解决方案
如果您知道所有不需要的字符,则可以使用.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"]
推荐阅读
- amazon-web-services - Aurora MySQL 5.6.10 中的 External_threads_connected 是什么意思
- r - 根据单独的列表/数据框 R 替换字符串
- go - grpc-go 模型中的空值问题
- php - 在 php 中写入用于记录的文件是一个性能阻止程序
- javascript - 使用客户端集成将变量 Amount 传递给 Smart PayPal 按钮是否安全?
- r - 如何从闪亮的应用程序下载 timevis 时间线
- build - Detox:如何为 Detox 配置提供 bitrise 构建路径以在 bitrise 上测试 E2E
- r - 如何修复闪亮的读取 xlsm 文件的行宽?
- javascript - 音频未在移动浏览器上加载(Plyr 播放器)
- vue.js - 如何通过路线名称转到子路线?