Skip to content

Commit d79e67a

Browse files
committed
新增字符处理的工具
1 parent abf0d60 commit d79e67a

1 file changed

Lines changed: 117 additions & 0 deletions

File tree

‎tools/char.py‎

Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
# coding=utf-8
2+
__author__ = 'zhanghe'
3+
4+
5+
"""
6+
字符处理的工具:
7+
判断unicode是否是汉字,数字,英文,或者其他字符。
8+
全角符号转半角符号。
9+
"""
10+
11+
12+
def is_alphabet(uchar):
13+
"""
14+
判断一个unicode是否是英文字母
15+
"""
16+
if (u'\u0041' <= uchar <= u'\u005a') or (u'\u0061' <= uchar <= u'\u007a'):
17+
return True
18+
else:
19+
return False
20+
21+
22+
def is_chinese(uchar):
23+
"""
24+
判断一个unicode是否是汉字
25+
"""
26+
if u'\u4e00' <= uchar <= u'\u9fa5':
27+
return True
28+
else:
29+
return False
30+
31+
32+
def is_number(uchar):
33+
"""
34+
判断一个unicode是否是数字
35+
"""
36+
if u'\u0030' <= uchar <= u'\u0039':
37+
return True
38+
else:
39+
return False
40+
41+
42+
def is_other(uchar):
43+
"""
44+
判断是否非汉字,数字和英文字符
45+
"""
46+
if not (is_chinese(uchar) or is_number(uchar) or is_alphabet(uchar)):
47+
return True
48+
else:
49+
return False
50+
51+
52+
def b2q(uchar):
53+
"""
54+
半角转全角
55+
"""
56+
inside_code = ord(uchar)
57+
if inside_code < 0x0020 or inside_code > 0x7e: # 不是半角字符就返回原来的字符
58+
return uchar
59+
if inside_code == 0x0020: # 除了空格其他的全角半角的公式为:半角=全角-0xfee0
60+
inside_code = 0x3000
61+
else:
62+
inside_code += 0xfee0
63+
return unichr(inside_code)
64+
65+
66+
def q2b(uchar):
67+
"""
68+
全角转半角
69+
"""
70+
inside_code = ord(uchar)
71+
if inside_code == 0x3000:
72+
inside_code = 0x0020
73+
else:
74+
inside_code -= 0xfee0
75+
if inside_code < 0x0020 or inside_code > 0x7e: # 转完之后不是半角字符返回原来的字符
76+
return uchar
77+
return unichr(inside_code)
78+
79+
80+
def string_q2b(ustring):
81+
"""
82+
把字符串全角转半角
83+
"""
84+
return "".join([q2b(uchar) for uchar in ustring])
85+
86+
87+
def uniform(ustring):
88+
"""
89+
格式化字符串,完成全角转半角,大写转小写的工作
90+
"""
91+
return string_q2b(ustring).lower()
92+
93+
94+
def string2list(ustring):
95+
"""
96+
将ustring按照中文,字母,数字分开
97+
"""
98+
ret_list = []
99+
u_tmp = []
100+
for uchar in ustring:
101+
if is_other(uchar):
102+
if len(u_tmp) == 0:
103+
continue
104+
else:
105+
ret_list.append("".join(u_tmp))
106+
u_tmp = []
107+
else:
108+
u_tmp.append(uchar)
109+
if len(u_tmp) != 0:
110+
ret_list.append("".join(u_tmp))
111+
return ret_list
112+
113+
114+
if __name__ == '__main__':
115+
print is_chinese(u'你好啊') # True
116+
print is_chinese(u'你abc') # True
117+
print is_chinese(u'abc你') # False

0 commit comments

Comments
 (0)