gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 17:04:14 24 4
gpt4 key购买 nike

我尝试使用 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()

最佳答案

重要的是显示字符的字体中字形的宽度,而不是作为 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

使用东亚宽度属性有效,因为

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 .

关于python - 使用python3查找表情符号的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63410948/

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