gpt4 book ai didi

python - 如何控制包含东亚字符的 Unicode 字符串的填充

转载 作者:太空狗 更新时间:2023-10-29 21:14:51 25 4
gpt4 key购买 nike

我得到了三个 UTF-8 字符串:

hello, world
hello, 世界
hello, 世rld

我只想要前 10 个 ascii-char-width,这样一列中的括号:

[hello, wor]
[hello, 世 ]
[hello, 世r]

在控制台中:

width('世界')==width('worl')
width('世 ')==width('wor') #a white space behind '世'

一个汉字是三个字节,但在控制台显示时只有2个ascii字符的宽度:

>>> bytes("hello, 世界", encoding='utf-8')
b'hello, \xe4\xb8\x96\xe7\x95\x8c'

当 UTF-8 字符混合时,python 的 format() 没有帮助

>>> for s in ['[{0:<{1}.{1}}]'.format(s, 10) for s in ['hello, world', 'hello, 世界', 'hello, 世rld']]:
... print(s)
...
[hello, wor]
[hello, 世界 ]
[hello, 世rl]

这不是很漂亮:

 -----------Songs-----------
| 1: 蝴蝶 |
| 2: 心之城 |
| 3: 支持你的爱人 |
| 4: 根生的种子 |
| 5: 鸽子歌(CUCURRUCUCU PALO|
| 6: 林地之间 |
| 7: 蓝光 |
| 8: 在你眼里 |
| 9: 肖邦离别曲 |
| 10: 西行( 魔戒王者再临主题曲)(INTO |
| X 11: 深陷爱河 |
| X 12: 钟爱大地(THE MO RUN AIR |
| X 13: 时光流逝 |
| X 14: 卡农 |
| X 15: 舒伯特小夜曲(SERENADE) |
| X 16: 甜蜜的摇篮曲(Sweet Lullaby|
---------------------------

那么,我想知道是否有一种标准的方法来处理 UTF-8 填充人员?

最佳答案

当尝试将 ASCII 文本与固定宽度字体的中文对齐时,有一组可打印 ASCII 字符的全角版本。下面我做了一个ASCII到全角版本的转换表:

# coding: utf8

# full width versions (SPACE is non-contiguous with ! through ~)
SPACE = '\N{IDEOGRAPHIC SPACE}'
EXCLA = '\N{FULLWIDTH EXCLAMATION MARK}'
TILDE = '\N{FULLWIDTH TILDE}'

# strings of ASCII and full-width characters (same order)
west = ''.join(chr(i) for i in range(ord(' '),ord('~')))
east = SPACE + ''.join(chr(i) for i in range(ord(EXCLA),ord(TILDE)))

# build the translation table
full = str.maketrans(west,east)

data = '''\
蝴蝶(A song)
心之城(Another song)
支持你的爱人(Yet another song)
根生的种子
鸽子歌(Cucurrucucu palo whatever)
林地之间
蓝光
在你眼里
肖邦离别曲
西行(魔戒王者再临主题曲)(Into something)
深陷爱河
钟爱大地
时光流逝
卡农
舒伯特小夜曲(SERENADE)
甜蜜的摇篮曲(Sweet Lullaby)
'''

# Replace the ASCII characters with full width, and create a song list.
data = data.translate(full).rstrip().split('\n')

# translate each printable line.
print(' ----------Songs-----------'.translate(full))
for i,song in enumerate(data):
line = '|{:4}: {:20.20}|'.format(i+1,song)
print(line.translate(full))
print(' --------------------------'.translate(full))

输出

 ----------Songs-----------
|   1: 蝴蝶(A song)          |
|   2: 心之城(Another song)   |
|   3: 支持你的爱人(Yet another s|
|   4: 根生的种子               |
|   5: 鸽子歌(Cucurrucucu palo|
|   6: 林地之间                |
|   7: 蓝光                  |
|   8: 在你眼里                |
|   9: 肖邦离别曲               |
|  10: 西行(魔戒王者再临主题曲)(Into s|
|  11: 深陷爱河                |
|  12: 钟爱大地                |
|  13: 时光流逝                |
|  14: 卡农                  |
|  15: 舒伯特小夜曲(SERENADE)    |
|  16: 甜蜜的摇篮曲(Sweet Lullaby|
 --------------------------

虽然不是很漂亮,但是很整齐。

关于python - 如何控制包含东亚字符的 Unicode 字符串的填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4622357/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com