Coder Social home page Coder Social logo

Calculate column width about prettytable HOT 4 CLOSED

pkodzis avatar pkodzis commented on June 30, 2024
Calculate column width

from prettytable.

Comments (4)

pkodzis avatar pkodzis commented on June 30, 2024 1

btw, if anybody needs, the code below does what I was looking for:

import re

def html2text(html_str):
    text = re.sub(r'<[^>]*>', '', html_str)
    return text.strip()


def mytable_print(data):
    headers = data[0]
    num_columns = len(headers)

    column_widths = [max(len(html2text(str(row[i])))
                         for row in data) for i in range(num_columns)]

    def print_row(row):
        row_str = ""
        for i in range(num_columns):
            text = str(row[i])
            padding = " " * (column_widths[i] - len(html2text(text)))
            row_str += f"| {text}{padding} "

        print(f"{row_str}|")

    def print_separator():
        separator = "+".join("-" * (width + 2) for width in column_widths)
        print(f"+{separator}+")

    print_separator()
    print_row(headers)
    print_separator()

    for row in data[1:]:
        print_row(row)

    print_separator()

if __name__ == "__main__":
    data = [['OSPF', 'Device', 'Interface', 'IP', 'Neighbor Device', 'Neighbor Interface', 'Neighbor IP', 'Up', 'Adjacency', 'ID', 'Pri', 'Timer', 'State'],
            ['', 'foo', '<a onclick="goJint(event,{\'device\':\'foo\',\'interface\':\'eth0\'});">eth0</a>', '10.10.10.64', 'test1', '<a onclick="goJint(event,{\'device\':\'test1\',\'interface\':\'eth101\'});">eth101</a>', '10.10.10.65', '46w6d 17:12:47', '46w6d 17:12:47', '192.168.1.36', '128', '38', 'Full'],
            ['', 'foo', '<a onclick="goJint(event,{\'device\':\'foo\',\'interface\':\'eth12\'});">eth2</a>', '10.10.10.66', 'test2', '<a onclick="goJint(event,{\'device\':\'test2\',\'interface\':\'vr0\'});">vr0</a>', '10.10.10.67', '46w6d 17:12:45', '46w6d 17:12:45', '192.168.1.37', '128', '31', 'Full']]
    mytable_print(data)

from prettytable.

hugovk avatar hugovk commented on June 30, 2024

Unfortunately PrettyTable doesn't have a way to do this.

from prettytable.

pkodzis avatar pkodzis commented on June 30, 2024

fair enough, thsank you for prompt response :)

from prettytable.

shifenhutu avatar shifenhutu commented on June 30, 2024

based on @pkodzis , support makrdown link

import re


def html2text(html_str):
    text = re.sub(r'<[^>]*>', '', html_str)
    return text.strip()


def md2text(html_str):
    pattern = r".*\|(\w+)>$"

    match = re.search(pattern, html_str)
    token = html_str
    if match:
        token = match.group(1)

    return token.strip()


def my_PrettyTable(data, type="markdown"):
    """
    支持 markdown 链接 ,html 等 (宽度会适应)
    """
    headers = data[0]
    num_columns = len(headers)

    match type:
        case "markdown":
            fun = md2text
        case "html":
            fun = html2text
        case _:
            fun = md2text

    column_widths = [max(len(fun(str(row[i])))
                         for row in data) for i in range(num_columns)]

    def print_row(row):
        row_str = ""
        for i in range(num_columns):
            text = str(row[i])
            padding = " " * (column_widths[i] - len(fun(text)))
            row_str += f"| {text}{padding} "
        return row_str

    def print_separator():
        separator = "+".join("-" * (width + 2) for width in column_widths)
        # print(f"+{separator}+")
        return f"+{separator}+"

    res = ""
    res = res + print_separator() + "\n"
    res = res + print_row(headers) + "|\n"
    res = res + print_separator() + "\n"


    for row in data[1:]:
        res = res + print_row(row) + "|\n"

    res = res + print_separator()

    return res


if __name__ == "__main__":
    data_html = [['OSPF', 'Device', 'Interface', 'IP', 'Neighbor Device', 'Neighbor Interface', 'Neighbor IP', 'Up', 'Adjacency', 'ID', 'Pri', 'Timer', 'State'],
            ['', 'foo', '<a onclick="goJint(event,{\'device\':\'foo\',\'interface\':\'eth0\'});">eth0</a>', '10.10.10.64', 'test1',
             '<a onclick="goJint(event,{\'device\':\'test1\',\'interface\':\'eth101\'});">eth101</a>', '10.10.10.65', '46w6d 17:12:47', '46w6d 17:12:47', '192.168.1.36', '128', '38', 'Full'],
            ['', 'foo', '<a onclick="goJint(event,{\'device\':\'foo\',\'interface\':\'eth12\'});">eth2</a>', '10.10.10.66', 'test2',
             '<a onclick="goJint(event,{\'device\':\'test2\',\'interface\':\'vr0\'});">vr0</a>', '10.10.10.67', '46w6d 17:12:45', '46w6d 17:12:45', '192.168.1.37', '128', '31', 'Full']]
    html_res = my_PrettyTable(data_html,type="html")

    print(html_res)

    data_md = [['url', 'gt_0', 'zhan_bi'], ['<https://google.com/111|1111111111>', 121, 0.0605], ['<https://google.com/111|111>', 106, 0.053], ['<https://google.com/111|111>', 74, 0.037], ['<https://google.com/111|111>', 72, 0.036], ['<https://google.com/111|111>', 71, 0.0355], ['<https://google.com/111|111>', 57, 0.0285]]
    md_res = my_PrettyTable(data_md, type="markdown")
    print(md_res)

from prettytable.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.