0
点赞
收藏
分享

微信扫一扫

爬虫文本数据清洗


def filter_chars(text):
"""过滤无用字符
:param text: 文本
"""
# 找出文本中所有非中,英和数字的字符
add_chars = set(re.findall(r'[^\u4e00-\u9fa5a-zA-Z0-9]', text))
extra_chars = set(r"""!!¥$%*()()-——【】::“”";;'‘’,。?,.?、""")
add_chars = add_chars.difference(extra_chars)
# tab 是/t
# 替换特殊字符组合
text = re.sub('{IMG:.?.?.?}', '', text)
text = re.sub(r'<!--IMG_\d+-->', '', text)
text = re.sub('(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]', '', text) # 过滤网址
text = re.sub('<a[^>]*>', '', text).replace("</a>", "") # 过滤a标签
text = text.replace("</P>", "")
text = text.replace("nbsp;", "")
text = re.sub('<P[^>]*>', '', text, flags=re.IGNORECASE).replace("</p>", "") # 过滤P标签
text = re.sub('<strong[^>]*>', ',', text).replace("</strong>", "") # 过滤strong标签
text = re.sub('<br>', ',', text) # 过滤br标签
text = re.sub('www.[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]', '', text).replace("()", "") # 过滤www开头的网址
text = re.sub(r'\s', '', text) # 过滤不可见字符
text = re.sub('Ⅴ', 'V', text)

# 清洗
for c in add_chars:
text = text.replace(c, '')
return text


举报

相关推荐

0 条评论