python 分割中文英文混合字符串的正确方法

python 里的字符编码不统一导致中英文的处理有不同的结果,下面介绍中文英文混合字符串 split 的方法。

python 中文英文混合split

分割词

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#!/usr/bin/env python
# -*- coding: utf-8 -*-

s = '我爱北京天安门python'

s2 = ''
if not isinstance(s, unicode):
    s2 = s.decode("utf-8")

slist = []
keys = []
for i in s2:
    print i
    slist.append(i)
    key = '%X' % ord(i)
    keys.append(key)

print len(slist)
print slist

print len(keys)
print keys

# =====================

s = u'我爱北京天安门python'
slist = []
keys = []
for i in s:
    if not isinstance(i, unicode):
        i = i.decode("utf-8")
    print i
    slist.append(i)
    key = '%X' % ord(i)
    keys.append(key)

print len(slist)
print slist

print len(keys)
print keys

用正则

1
2
3
4
5
6
import re
 
s = 'hi新手oh'.decode('utf-8') #举个栗子是字符串s,为了匹配下文的unicode形式,所以需要解码
p = re.compile(ur'[\u4e00-\u9fa5]') #这里是精髓,[\u4e00-\u9fa5]是匹配所有中文的正则,因为是unicode形式,所以也要转为ur
 
print p.split(s) #使用re库的split切割

稍复杂的分切

中文按字断开,英文按单词分开,数字按空格等特殊符号断开

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import re

def get_word_list(s1):
    # 把句子按字分开,中文按字分,英文按单词,数字按空格
    regEx = re.compile('[\\W]*')    # 我们可以使用正则表达式来切分句子,切分的规则是除单词,数字外的任意字符串
    res = re.compile(r"([\u4e00-\u9fa5])")    #  [\u4e00-\u9fa5]中文范围

    p1 = regEx.split(s1.lower())
    str1_list = []
    for str in p1:
        if res.split(str) == None:
            str1_list.append(str)
        else:
            ret = res.split(str)
            for ch in ret:
                str1_list.append(ch)

    list_word1 = [w for w in str1_list if len(w.strip()) > 0]  # 去掉为空的字符

    return  list_word1

本文网址: https://pylist.com/topic/48.html 转摘请注明来源

Suggested Topics

python中文链接安全转码

当一个链接里包含中文时,有些浏览器并不能正确解析,这就需要首先对中文作安全转码,这里介绍用 python中文链接安全转码,...

3行 Python 代码解简单的一元一次方程

一元一次方程:只含有一个未知数(即“元”),并且未知数的最高次数为1(即“次”)的整式方程叫做一元一次方程(英文名:`linear equation with one unknown`)。...

Leave a Comment