0. 问题描述
- 抓取到的评论数据非常滴脏,其中有一些无用信息,所以目标就是只提取其中的中文文字内容
- 评论中会存在很多表情,如下所示
不是很快就撤了吗? <span class="url-icon"><img alt="[吃瓜]" src="//h5.sinaimg.cn/m/emoticon/icon/default/d_chigua-90cb948c34.png" style="width:1em; height:1em;"/></span>
实际上展现出的内容则是:

这一种类型的表情是微博特有的表情,还有一种是Emoji 表情,前者会在评论内容嵌入html代码,后者则是会已编码的方式呈现。
- 评论中的@符号: @符后也会跟随中文这些需要,用专门的代码过滤掉
1.解决思路
- 表情问题:
用正则表达式过滤,表达式如下[\u4e00-\u9fa5,。!??! ]{1,}
- @问题:
经过观察 @的内容全部在a标签内,所以显而易见只需要把所有<a ... </a>之内的内容即可
2.代码实例
#匹配中文的正则表达式
self.pattern = re.compile(r"[\u4e00-\u9fa5,。!??! ]{1,}")
def remove_text_dirty(self,oldstr):
logging.info("oldstr:" + oldstr)
oldstr = oldstr.replace("\n", "")#去掉评论所有的换行符
count = oldstr.count("<a")#统计评论中<a>标签的数量
for i in range(0,count): # 对评论中<a>标签逐一进行处理
if oldstr.count("<a") is 0: #如果评论中没有<a>标签
break
font = oldstr.index("<a")
tail = oldstr.index("</a>")
dirty = oldstr[font:tail+4] #获取到评论中当前<a>标签的内容
oldstr = oldstr.replace(dirty,"") #去除评论中当前<a>标签的内容
logging.info("newstr:"+oldstr)
match = self.pattern.match(oldstr)
logging.info("match:"+str(match))
if match:
#返回匹配到的中文内容
return match.group()
else:
#没有中文返回汉字
return None
网友评论