利用正则表达式识别文本中的中文

我们在利用正则表达式识别中文时,使用Unicode字符范围来匹配中文数字,而Unicode的范围为\ue4e00-\u9fff。

import re
def extract_chinese_chars(code):
    chinese_pattern = '[\u4e00-\u9fff]+'  # 匹配中文字符
    chinese_chars = re.findall(chinese_pattern, code)
    return chinese_chars
# 测试代码
code = '''梅西是最好的,messi is the best'''
chinese_chars = extract_chinese_chars(code)
print("中文字符:", chinese_chars)

如果要对字符类进行匹配,我们需要更改pattern为[a-zA-Z]

import re
def extract_chinese_chars(code):
    english_pattern = '[a-zA-Z]+'  # 匹配中文字符
    chinese_chars = re.findall(english_pattern, code)
    return chinese_chars
# 测试代码
code = '''梅西是最好的,messi is the best'''
english_chars = extract_chinese_chars(code)
print("中文字符:", english_chars)

正则表达式具有强大的文本模式匹配,对字符串进行搜索,匹配,替换和提取。

猜你喜欢

转载自blog.csdn.net/qq_52351946/article/details/131154197