2014-04-14 76 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 
相關問題