我想删除文本中的字母数字字符。例如,我有如下文本:
text= I want to remove alphanumeric jhanb562nkk from the text. Remove alphanumeric from all the texts. uhufshfn76429 is very hard to figure out.
预期结果
result=I want to remove alphanumeric from the text. Remove alphanumeric from all the texts. is very hard to figure out.
我不确定如何使用regex/replace方法从文本中删除它们。
您可以使用以下正则表达式:[A-Za-z]+[d]+[w]*|[d]+[A-Za-z]+[w]*
函数调用为:re.sub(rgx_str, '', text)
请注意,这将在清除字母数字文本的任何位置留下额外的空间。删除此项的一个简单方法是运行另一个regex进行后期处理:" +"
并替换为" "
。
从您的问题中不清楚您是否需要使用regex,或者您对任何解决方案都满意。如果您不必使用regex,这里有一个使用列表理解的答案:
s = 'some con123taminated pure 123 words'
filtered_str = [word for word in s.split() if (all(ch.isdigit() for ch in word) or not any(ch.isdigit() for ch in word))]
filtered_str = ' '.join(filtered_str)
我承认它不容易阅读。但唯一可能不清楚的比特是all(.) or not any(.)
部分。它基本上确保单词中的所有字符都是数字,或者没有数字。