网络编程
位置:首页>> 网络编程>> Python编程>> python用正则表达式提取/匹配中文汉字

python用正则表达式提取/匹配中文汉字

作者:一位代码  发布时间:2021-06-12 23:45:50 

标签:正则表达式,匹配,中文

python用正则表达式提取中文

Python re正则匹配中文,其实非常简单,把中文的unicode字符串转换成utf-8格式就可以了,然后可以在re中随意调用

unicode中中文的编码为/u4e00-/u9fa5,因此正则表达式u”[\u4e00-\u9fa5]+”可以表示一个或者多个中文字符

>>> import re

>>> s='中文:123456aa哈哈哈bbcc'.decode('utf8')
>>> s
u'\u4e2d\u6587\uff1a123456aa\u54c8\u54c8\u54c8bbcc'
>>> print s
中文:123456aa哈哈哈bbcc

>>> re.match(u"[\u4e00-\u9fa5]+",s)
<_sre.SRE_Match object at 0xb77742c0>

>>> pat='中文'.decode("utf8")
>>> re.search(pat,s)
<_sre.SRE_Match object at 0x16a16df0>

>>> newpat='这里是中文内容'.decode("utf8")

>>> news=re.sub(pat,newpat,s)
>>> print news

这里是中文内容:123456aa哈哈哈bbcc

python正则如何匹配中文汉字

正则表达式匹配中文汉字,在实际应用中十分常见。

比如:爬虫网页文本提取、验证用户输入标准等。

以下面文本字符串为例,匹配出astr这个字符串中的所有汉字。

import re
astr = '''aaaaa何时when 杖尔看see南雪snow,我me与梅花plum blossom两白头'''

下面介绍两种方法(本文环境为python3)

一、使用Unicode编码来匹配中文

常见的中文Unicode编码范围:\u4e00-\u9fa5

实现匹配代码:re.findall(&rsquo;[\u4e00-\u9fa5]&rsquo;, astr)

import re
astr = '''aaaaa何时when 杖尔看see南雪snow,我me与梅花plum blossom两白头'''
res = re.findall('[\u4e00-\u9fa5]', astr)
print(res)

匹配结果:

python用正则表达式提取/匹配中文汉字

二、直接使用中文汉字实现中文匹配

没使用过可能还真不知道,中文匹配还可以这样

实现匹配代码:re.findall(&rsquo;[一-龥]&rsquo;, astr)

import re
astr = '''aaaaa何时when 杖尔看see南雪snow,我me与梅花plum blossom两白头'''
res = re.findall('[一-龥]', astr)
print(res)

匹配结果:

python用正则表达式提取/匹配中文汉字

注:其实这里&ldquo;一&rdquo;对应的Unicode编码就是&ldquo;\u4e00&rdquo;,&ldquo;龥&rdquo;(y&ugrave;)对应的Unicode编码就是&ldquo;\u9fa5&rdquo;。

常见非英文字符Unicode编码范围:

u4e00-u9fa5 (中文)
u0800-u4e00 (日文)
uac00-ud7ff(韩文)

来源:https://blog.csdn.net/LHJCSDNYL/article/details/122164430

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com