Python 文本过滤:去除所有特殊字符,保留纯文本内容
可以使用正则表达式来过滤文本中的特殊字符。以下是一个示例代码:
import re
def filter_special_chars(text):
pattern = r'[^a-zA-Z0-9\s]' # 匹配非字母、非数字、非空白字符
filtered_text = re.sub(pattern, '', text)
return filtered_text
# 测试
text = 'Hello! How are you? #Python'
filtered_text = filter_special_chars(text)
print(filtered_text) # 输出: Hello How are you Python
在上述代码中,filter_special_chars 函数使用 re.sub 函数来替换文本中匹配正则表达式 [^a-zA-Z0-9\s] 的特殊字符为空字符串,从而实现过滤特殊字符的功能。
原文地址: https://www.cveoy.top/t/topic/quxg 著作权归作者所有。请勿转载和采集!