Python: 日本語(および東アジア言語)のマルチバイト文字の幅を調べる
ターミナル周りの処理では、Unicode の文字列を文字の幅によって表示を整えたい場合が往々にしてある。
このようなとき Python では、unicodedata モジュールの east_asian_width 関数を使えばよい。
こちらの記事が大変分かりやすく参考になった。
【UTF8文字幅揃え】unicodedata.east_asian_width(): Pythonと自分 ~ a python life
実装例 (ジェネレータ式を使用。Python 2.4~)
1 2 3 4 5 6 7 8 9 10 | def unicode_width(s, width = { 'F' : 2 , 'H' : 1 , 'W' : 2 , 'Na' : 1 , 'A' : 2 , 'N' : 1 }): from unicodedata import east_asian_width return sum (width[east_asian_width(c)] for c in s) print (unicode_width(u 'A' )) # 2 (Fullwidth) print (unicode_width(u 'ア' )) # 1 (Halfwidth) print (unicode_width(u 'あ' )) # 2 (Wide) print (unicode_width(u 'A' )) # 1 (Narrow) print (unicode_width(u 'α' )) # 2 (Ambiguous) print (unicode_width(u 'ς' )) # 1 (Neutral) |
0 件のコメント:
コメントを投稿