Reprinted: http://likang.me/blog/2012/04/13/calculate-character-width-in-python/
Recently, I am writing a small CLI program in python, which involves calculating the width of characters. The goal is to truncate a long string into equal-width segments in a friendly way.
For unicode characters, python's len function can accurately calculate the number of characters contained in it, but the number does not represent the width, such as:
>>>len(u'你好a')
3
Therefore, it is not possible to simply use this method to calculate the width.
GBK decode
First of all, I thought of GBK encoding. The characters in the range of 00–7F are one-byte encoding, and the rest are two-byte encoding, which is roughly the same as the width of the characters, so there is such an opportunistic method (assuming 8 widths):
>>> a = u'hello你好'
>>> b=a.encode('gbk')
>>> try:
... print b[:8].decode('gbk')
... except:
... print b[:7].decode('gbk')
...
hello你
As shown in the code, first encode the unicode string with GBK, and then try to decode it with GBK after intercepting the width of 8 bytes.
Although the problem has been initially solved, the flaws in doing so are obvious. First, the code is not elegant and runs in a trial-and-error manner; secondly, the characters that GBK can represent are limited and cannot support a large number of characters other than GBK encoding.
East_Asian_Width
After wandering around for a long time, I stumbled across the East_Asian_Width property in the Unicode Character Database standard, with the following possible values:
# East_Asian_Width (ea)
ea ; A ; Ambiguous 不确定
ea ; F ; Fullwidth 全宽
ea ; H ; Halfwidth 半宽
ea ; N ; Neutral 中性
ea ; Na ; Narrow 窄
ea ; W ; Wide 宽
Among them, except that A is uncertain, F/H/N/Na/W can clearly know the width. If A is regarded as a width of 2 to be conservative, it is easy to give the width of a single character:
>>> import unicodedata
>>> def chr_width(c):
... if (unicodedata.east_asian_width(c) in ('F','W','A')):
... return 2
... else:
... return 1
>>> chr_width(u'你')
2
>>> chr_width(u'a')
1
It seems that it can meet the requirements so far, but it is not uncommon to find characters with attribute A in actual use. The most typical one is Chinese double quotation marks:
>>> chr_width(u'”')
2
In most monospaced fonts, Chinese double quotation marks occupy only one digit wide. If there are multiple Chinese double quotation marks in a line, the accumulated misjudgment width will greatly reduce the interception effect, which is undoubtedly not the best. way.
urwid's solution
urwid是一个成熟的python终端UI库,它在curses的基础之上包装了类似HTML的控件用以显示文本内容,如果有这方面的开发需求,非常推荐此库,比直接使用curses库方便很多,非常棒的是它对unicode的文本宽度截取非常准确,让我大为惊讶,于是翻开它的源码一探究竟,文本宽度计算方面其核心代码如下:
widths = [
(126, 1), (159, 0), (687, 1), (710, 0), (711, 1),
(727, 0), (733, 1), (879, 0), (1154, 1), (1161, 0),
(4347, 1), (4447, 2), (7467, 1), (7521, 0), (8369, 1),
(8426, 0), (9000, 1), (9002, 2), (11021, 1), (12350, 2),
(12351, 1), (12438, 2), (12442, 0), (19893, 2), (19967, 1),
(55203, 2), (63743, 1), (64106, 2), (65039, 1), (65059, 0),
(65131, 2), (65279, 1), (65376, 2), (65500, 1), (65510, 2),
(120831, 1), (262141, 2), (1114109, 1),
]
def get_width( o ):
"""Return the screen column width for unicode ordinal o."""
global widths
if o == 0xe or o == 0xf:
return 0
for num, wid in widths:
if o <= num:
return wid
return 1
如代码所示,首先根据unicode的官方EastAsianWidth文档整理出字符宽度的范围表,然后使用unicode代码查表。使用之前的例子测试:
>>> get_width(ord(u'a'))
1
>>> get_width(ord(u'你'))
2
>>> get_width(ord(u'”'))
1
完全准确,而且在实际应用中的表现也比较好,是一个理想的解决方案,更多技巧请查阅urwid的old_str_util.py源码。