在 Python3 中打印涉及英语和日语文本的右对齐 table 列

Print right aligned table column involving English and Japanese text in Python3

我有一个由英文和日文字符组成的列,我需要以右对齐方式打印该列。

这是我应该打印的专栏:

column = ["通常残業時間", "bbbbbbbbb", "tttt"]

通常的方法是获取字符串的最大长度并相应地进行调整,但问题是文本也是日文的,而且日文字符的宽度比英文字符的宽度大。在这种情况下我应该如何比较字符串长度并相应地打印?

这是所需的输出:

通常残業時間
 bbbbbbbbb
      tttt

我在Python3工作。

问题是日文字符的宽度比英文字符宽一点点 space.' '

这种情况是有解决办法的。你只需要计算这两种语言的宽度即可。

columns = ["通常残業時間", "bbbbbbbbb", "tttt"]
for i in column:
    print('|'.join(list(i)))

你可以得到一些类似的东西。

通|常|残|業|時|間
b|b|b|b|b|b|b|b|b
t|t|t|t

您可以使用 | 找到宽度的关系。 在这里,我认为,它看起来几乎像 5 个日文等于 9 个英文字符(不要忘记减去 |。)

当你得到宽度关系时。

那么我想你可能知道如何计算它们应该适合的长度。


对于以上错误或误导性的建议,我们深表歉意。我意识到除非找到 space 的不同宽度以适应不同的语言字符,否则无法使其对齐。

但我想我可能会发现一些关于这个的相关问题和一些有用的包。

Display width of unicode strings in Python [duplicate]

kitchen.text.display.textual_width 只是为了 python2.7 很遗憾...

似乎汉字(和中文)字母的长度是 ascii 的两倍。

因此,我将使用 .encode('ascii')UnicodeEncodeError 来检查一行是否为 ascii。 (基于此处的回答:)

如果是ascii,我们需要在行前多加空格。

这是一个解决方案:

words = ["hhhh", "你你你你你你"]
max_length = 0

# Find the max length string in the array
# For kanji strings, the max length is doubled
for line in words:
    line_length = 0
    try:
        line.encode('ascii')
    except UnicodeEncodeError:
        line_length = 2 * len(line)
    else:
        line_length = len(line)
    if max_length < line_length:
        max_length = line_length

# Find the number of spaces to add by subtracting max line length by length of current line
# If current line is kanji, it is twice a ascii string length
for line in words:
    space = 0
    try:
        line.encode('ascii')
    except UnicodeEncodeError:
        space = max_length - (len(line)*2)
    else:
        space = max_length - len(line)
    print((' ')*space + line)

输出:

        hhhh
你你你你你你

第一行是4个ascii字符长。第二行是6个汉字长==12个ascii字符长。所以第一行前面需要 12-4=8 个空格 (MONOSPACE!!!)。它在 Whosebug 中看起来不正确,但在终端中它会由于等宽字体而对齐。

顺便说一句,我用 Python3 写了这个解决方案。

您可以在 column 的最后两项上使用 r.just

column = ["通常残業時間", "bbbbbbbbb", "tttt"]

for idx, item in enumerate(column):
    if not idx:
        print(item)
    else:
        print(item.rjust(12))
通常残業時間
 bbbbbbbbb
      tttt