前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python提取中文字符

Python提取中文字符

作者头像
致Great
发布2019-02-13 10:16:02
3.5K0
发布2019-02-13 10:16:02
举报
文章被收录于专栏:程序生活

写这个jupyter的原因是好几次自己爬完新闻之后,发现中间有些是html标签代码或者其他多余的英文字符,自己也不想保留,那么这时候一个暴力简单的方法就是使用 unicode 范围 \u4e00 - \u9fff 来判别汉字

unicode 分配给汉字(中日韩越统一表意文字)的范围为 4E00-9FFF (目前 unicode 6.3 的标准已定义到 9FCC )

代码语言:javascript
复制
# 判断字符是否全是中文
def ishan(text):
    # for python 3.x
    # sample: ishan('一') == True, ishan('我&&你') == False
    return all('\u4e00' <= char <= '\u9fff' for char in text)
代码语言:javascript
复制
ishan("asas112中国")
代码语言:javascript
复制
False
代码语言:javascript
复制
# 提取中文字符
import re
def extract_chinese(txt):
    pattern = re.compile("[\u4e00-\u9fa5]")
    return "".join(pattern.findall(txt))
extract_chinese("任命的。</p> <p>3G资本成立于2004年,是")
代码语言:javascript
复制
'任命的资本成立于年是'

还有一个是过滤HTML标签的强大工具

HTMLParser

代码语言:javascript
复制
from html.parser import HTMLParser
def strip_tags(html):
    """
    Python中过滤HTML标签的函数
    >>> str_text=strip_tags("<font color=red>hello</font>")
    >>> print str_text
    hello
    """
    html = html.strip()
    html = html.strip("\n")

    result = []
    parser = HTMLParser()
    parser.handle_data = result.append
    parser.feed(html)
    parser.close()
    result=''.join(result)
    result = result.replace("\n", "")
    return result
代码语言:javascript
复制
strip_tags("<font color=red>hello</font>")
代码语言:javascript
复制
'hello'
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019.01.11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档