python提取中文字符

编程入门 行业动态 更新时间:2024-10-21 22:55:27

python提取<a href=https://www.elefans.com/category/jswz/34/1769975.html style=中文字符"/>

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 = repile("[\u4e00-\u9fa5]")

return "".join(pattern.findall(txt))

extract_chinese("任命的。

3G资本成立于2004年,是")

'任命的资本成立于年是'

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

HTMLParser

from html.parser import HTMLParser

def strip_tags(html):

"""

Python中过滤HTML标签的函数

>>> str_text=strip_tags("hello")

>>> 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("hello")

'hello'

更多推荐

python提取中文字符

本文发布于:2024-03-23 15:30:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1739801.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中文   字符   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!