python在windows、linux控制台对齐显示csv数据表格

一个python小模块,在windows、linux控制台对齐显示csv数据表格。
写的时候,调整对齐稍微有点费劲的。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from sre_parse import fix_flags

def is_in_linux():
    os_name = platform.system()
    if os_name == "Linux":
        return True
    return False


def get_display_width(text):
    """计算字符串的显示宽度,考虑中文字符"""
    width = 0
    for char in text:
        if unicodedata.east_asian_width(char) in ("F", "W"):
            width += 2
        else:
            width += 1
    return width


def get_display_width_without_color(text):
    """获取不考虑颜色标识的字符串宽度"""
    width = 0
    color_pattern = re.compile("\033\[\d+m")  # 颜色标识的正则表达式
    cleaned_text = re.sub(color_pattern, "", text)  # 去除颜色标识
    for char in cleaned_text:
        if unicodedata.east_asian_width(char) in ("F", "W"):
            width += 2
        else:
            width += 1
    return width


def align_string(text, width):
    """根据指定宽度对字符串进行对齐"""
    text_width = get_display_width(text)
    padding = width - text_width
    if padding > 0:
        return text + " " * padding
    return text


def align_string_without_color(text, width):
    """根据指定宽度对字符串进行对齐"""
    text_width = get_display_width_without_color(text)
    padding = width - text_width
    if padding > 0:
        return text + " " * padding
    return text


def display_csv_file_windows(csv_file_path):
    with open(csv_file_path, "r", newline="", encoding="utf-8") as file:
        reader = csv.reader(file)
        max_widths = []
        rows = list(reader)
        # 获取每列的最大字符宽度
        for row in rows:
            for i, value in enumerate(row):
                if i >= len(max_widths):
                    max_widths.append(0)
                width = get_display_width(value) if value else 1  # 将空字符串视为宽度为1的单元格
                max_widths[i] = max(max_widths[i], width)

        # 打印顶部边框
        top_border = "+-" + "-+-".join(["-" * width for width in max_widths]) + "-+"
        print(top_border)

        # 打印对齐的CSV数据
        for row in rows:
            formatted_row = []
            for i, value in enumerate(row):
                formatted_value = value if value else " "  # 将空字符串替换为一个空格
                formatted_value = align_string(formatted_value, max_widths[i])
                formatted_row.append(formatted_value)
            print("| " + " | ".join(formatted_row) + " |")

            # 打印行与行之间的分隔线
            print("+-" + "-+-".join(["-" * width for width in max_widths]) + "-+")


def display_csv_file_linux(csv_file_path):
    with open(csv_file_path, "r", newline="", encoding="utf-8") as file:
        reader = csv.reader(file)
        max_widths = []
        rows = list(reader)
        # 获取每列的最大字符宽度
        for row in rows:
            for i, value in enumerate(row):
                if i >= len(max_widths):
                    max_widths.append(0)
                width = get_display_width(value) if value else 1  # 将空字符串视为宽度为1的单元格
                max_widths[i] = max(max_widths[i], width)
        # 打印顶部边框
        top_border = (
            "+-" + "-+-".join(["-" * (width + 2) for width in max_widths]) + "-+"
        )
        print(top_border)
        # 打印对齐的CSV数据
        for i, row in enumerate(rows):
            formatted_row = []
            for j, value in enumerate(row):
                formatted_value = value if value else " "  # 将空字符串替换为一个空格
                if i == 0 or j == 0:
                    formatted_value = "\033[94m" + formatted_value + "\033[0m"  # 标蓝文本
                formatted_value = align_string_without_color(
                    formatted_value, max_widths[j]
                )
                formatted_row.append(formatted_value)
            print("| " + "   | ".join(formatted_row) + "   |")
            # 打印行与行之间的分隔线
            print("+-" + "-+-".join(["-" * (width + 2) for width in max_widths]) + "-+")


def display_csv_file(csv_file_path):
    if is_in_linux():
        # command = f"column -s, -t < {csv_file_path}" # linux自带的没有边框。
        # subprocess.run(command, shell=True)
        display_csv_file_linux(csv_file_path)
    else:
        display_csv_file_windows(csv_file_path)
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
PythonWindows 控制台中遇到中文显示乱码的情况,通常是由于字符编码设置不正确导致的。以下是解决步骤: 1. **确认默认代码页**:Windows 控制台默认使用 GBK 或 CP936 编码。你可以通过打开“控制面板”>“区域和语言”>“系统”>“高级”>“环境变量”,查看“系统变量”中的“当前默认代码页”是否为正确的中文编码。 2. **设置命令提示符(CMD)或 PowerShell 的编码**: - 在 CMD 中,右键点击图标,选择“属性”,然后在“常规”标签下,点击“更改系统变量”,在“新值”栏中输入“chcp 65001”并应用,这会将默认编码设为 UTF-8。 - 对于 PowerShell,打开“首选项”>“PowerShell选项”,在“配置”部分,点击“Ctrl+Shift+`”打开“Windows PowerShell ISE”(集成化命令行环境),切换到“环境”选项卡,找到“默认编码”并设置为“UTF-8”。 3. **代码文件编码**:如果你是在运行包含中文的 `.py` 文件,确保文件本身的编码是 UTF-8。在文本编辑器中,如 Notepad++,可以选择“另存为”并选择正确的编码。 4. **重新加载终端**:更改设置后,可能需要关闭并重新打开控制台窗口,让设置生效。 相关问题: 1. 如何在Python脚本中指定输出字符编码? 2. 为什么在CMD中设置UTF-8编码后中文仍然显示乱码? 3. PowerShell如何设置与CMD不同的字符编码?

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值