使用python3查找表情符号的宽度

2024-06-28 18:45:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用python中的模式打印字母“A”

def printA(length,height,symbol):
    a = [[" " for i in range(length)] for i in range(height)]
    for i in range(height):
        for j in range(length):
            if j == 0 or i == 0 or i == height // 2 or j == length - 1:a[i][j] = symbol
    return a

它适用于普通字符,如*,/+,-,#,$,% .. etc.,

输出: 正常字符

#######
#     #
#     #
#######
#     #
#     #
#     #

表情符号

😀😀😀😀😀😀😀
😀     😀
😀     😀
😀😀😀😀😀😀😀
😀     😀
😀     😀
😀     😀

如果我能找到表情符号的长度,那么我就可以将空格改为表情符号的长度,这样就不会出现这个问题,有没有办法

Note : The above code works only for characters and not strings

编辑:
snakecharmerb's应答开始,它只适用于打印字符A,但当我尝试打印A的序号时,即不止一次,它只是将表情放错了位置

示例:我试图打印AAAAA

输出:

从上面的输出来看,当我们增加字母的位置时,它会重新定位自身,有没有办法防止这种情况发生

我是这样打印的AAAAA

a = printA(7,7,"😀")
for i in a:
    for k in range(5):print(*(i),end="  ")
    print()

Tags: orinfor字母rangesymbol字符length
2条回答

您可以使用以下内容检查长度

len("😀".encode("utf-8"))

在这两个堆栈溢出响应中可以找到更多信息

Find there is an emoji in a string in python3

How to extract all the emojis from text?

除了算出表情符号的长度,你不能这样做吗

a = [[" "*len(symbol) for i in range(length)] for i in range(height)]

重要的是显示字符的字体中字形的宽度,而不是作为Python字符串的字符长度。Python无法获得此信息,但我们可以根据symbol是否是wide East Asian character进行猜测,正如unicodedata模块报告的unicode标准所定义的那样

import unicodedata 


def printA(length, height, symbol):  
    # Two spaces for "wide" characters, one space for others.
    spacer = '  ' if unicodedata.east_asian_width(symbol) == 'W' else ' ' 
    a = [[spacer for i in range(length)] for i in range(height)]  
    for i in range(height): 
        for j in range(length): 
            if j == 0 or i == 0 or i == height // 2 or j == length - 1:
                a[i][j] = symbol  
    return a

使用East Asian Width属性有效,因为

emoji characters were first developed through the use of extensions of legacy East Asian encodings, such as Shift-JIS, and in such a context they were treated as wide characters. While these extensions have been added to Unicode or mapped to standardized variation sequences, their treatment as wide characters has been retained, and extended for consistency with emoji characters that lack a legacy encoding.

link

您可能还需要检查终端是否使用单间距字体

另请参见this Q&A,了解有关在终端中使用不同字符宽度属性对齐文本的一些问题,以及thisthis

相关问题 更多 >