Python提取中文字符

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

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

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

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

HTMLParser

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
strip_tags("<font color=red>hello</font>")
'hello'
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值