我需要使用 .isalpha() 和 .isdigit() 过滤掉所有不是字母或数字的东西。
目前正在做定义和.replace()。
问问题
301 次
3 回答
1
def remove_special_chars(string):
output = []
for c in string:
if c.isalpha() or c.isdigit();
output.append(c)
return ''.join(output)
于 2020-11-20T02:04:03.190 回答
0
使用正则表达式拆分和过滤以及 isdigit 和 isalpha
sentence ="1 I have bought several of the Vitality canned dog food products and have found them all to be of good quality. huh? The product looks more like a stew than a processed meat and it smells better-looks better. My Labrador is finicky-pampered and she appreciates this product better than most."
sentence=sentence.lower()
words=re.split("[, |-|\?|\!|\.]",sentence)
words=filter(lambda w: ((w.isdigit() or w.isalpha()) and len(w)>0),words)
print(*words)
输出:
1 i have bought several of the vitality canned dog food products and have found them all to be of good quality huh the product looks more like a stew than a processed meat and it smells better my labrador is and she appreciates this product better than most
于 2021-08-20T20:15:11.033 回答
0
您可以通过以下方式轻松实现:
from sets import Set
allowed_chars = Set('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
validationString = 'inv@lid'
if Set(validationString).issubset(allowed_chars):
return validationString # nothing to remove from this string
else:
return ''.join(i for i in validationString if Set(i).issubset(allowed_chars))
于 2020-11-19T21:54:37.473 回答