2014-04-14 70 views
1

我要检查一个字符是否是全角半角或全角半角或使用Python检查字符是在Python

string="你好hallo" 
for char in string: 
    if(\uFF60- \u0f01 and \uFFE0-\uFFE6): print(char +"is fullwidth") 
    elif(\uFF61-\uFFDC and \uFFE8-\uFFEE):print(char+ " is halfwidth") 

请帮我改变这种伪成真正的Python代码。

回答

4

您可以检查使用unicodedata.east_asian_width(unichr)字符的宽度:

import unicodedata 

for char in string: 
    status = unicodedata.east_asian_width(char) 
    if status == 'F': 
     print('{0} is full-width.'.format(char)) 
    elif status == 'H': 
     print('{0} is half-width.'.format(char)) 
+0

我也得到''Na''的状态,如果该字符不是亚洲。 –

+0

@MarkRansom所有Unicode字符都有东亚宽度。 –

+0

看来我的Python版本(2.7.5)与你的不同。我只是再次检查:>>> print unicodedata.east_asian_width(u'x') Na' –

3

亚历克斯桑顿提到的,使用unicodedata.east_asian_width()是正确的。然而,它具有以下的返回值:

# East_Asian_Width (ea) 

ea ; A   ; Ambiguous 
ea ; F   ; Fullwidth 
ea ; H   ; Halfwidth 
ea ; N   ; Neutral 
ea ; Na  ; Narrow 
ea ; W   ; Wide 

'W''F''A'返回值应被视为在Windows全宽。

参考:http://www.unicode.org/reports/tr44/tr44-4.html#Validation_of_Enumerated


在POSIX平台上,引号字符(u'“'u'”')被认为是暧昧,这实际上在控制台1个字符宽度。在这里,您可以尝试第三方库urwid代替:

>>> from urwid.util import str_util 
>>> str_util.get_width(ord(u'x')) 
1 
>>> str_util.get_width(ord(u'“')) 
1 
>>> str_util.get_width(ord(u'你')) 
2 
相关问题