马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
大佬们求助,写了个tabular_printing()函数用于表格样式打印数据,但是含有中文的部分没法对齐,如下图所示:
from faker import Faker
from typing import List, Tuple
def generate_data(faker):
return (
faker.name(),
faker.country(),
faker.phone_number(),
faker.ssn(),
faker.ascii_free_email(),
faker.date(),
faker.company()
)
element = Tuple[str, str, str, str, str, str, str]
fk1 = Faker(locale="en_US")
fk2 = Faker(locale="zh_CN")
data = [generate_data(faker=fk1) for _ in range(10)]
data.insert(2, generate_data(faker=fk2))
def tabular_printing(headers: Tuple, data: List) -> None:
table_rows = [headers]
table_rows.extend((str(i),) + row for i, row in enumerate(iterable=data, start=1))
column_widths = [max(len(str(item)) for item in col) for col in zip(*table_rows)]
separator = f"+{'+'.join('-' * (w + 2) for w in column_widths)}+"
sheet = [separator]
for row in table_rows:
sheet.append(f"|{'|'.join(f' {item:^{w}} ' for item, w in zip(row, column_widths))}|")
sheet.append(separator)
print(*sheet, sep="\n")
if __name__ == '__main__':
headers = ("", "Name", "Country", "PhoneNumber", "IDCard", "E-mail", "Birthday", "Company")
tabular_printing(headers=headers, data=data)
|