本文目录导读:

- Python + pandas(推荐)
- Python + prettytable(美观表格)
- Bash + awk(Linux/Mac)
- Node.js + table库
- 通用JavaScript函数
- 快速使用示例
Python + pandas(推荐)
import pandas as pd
from io import StringIO
# 原始文本数据
text_data = """姓名,年龄,城市
张三,25,北京
李四,30,上海
王五,28,广州"""
# 方式1:从CSV格式文本读取
df = pd.read_csv(StringIO(text_data))
# 方式2:从带分隔符的文本读取
text_data2 = """姓名|年龄|城市
张三|25|北京
李四|30|上海"""
df2 = pd.read_csv(StringIO(text_data2), sep='|')
# 格式化输出
print("表格显示:")
print(df.to_string(index=False))
print("\nMarkdown格式:")
print(df.to_markdown())
print("\nHTML表格:")
print(df.to_html())
Python + prettytable(美观表格)
from prettytable import PrettyTable
def text_to_table(text, delimiter=','):
"""文本转表格"""
lines = text.strip().split('\n')
# 创建表格对象
table = PrettyTable()
# 设置表头
headers = lines[0].split(delimiter)
table.field_names = headers
# 添加数据行
for line in lines[1:]:
row = line.split(delimiter)
table.add_row(row)
# 设置样式
table.align = 'l' # 左对齐
table.padding_width = 2 # 内边距
return table
# 使用示例
text = """产品,价格,库存
苹果,5.5,100
香蕉,3.2,50
橙子,4.8,80"""
table = text_to_table(text)
print(table)
Bash + awk(Linux/Mac)
#!/bin/bash
# 文本转表格脚本
cat << 'EOF' | awk -F',' '
BEGIN {
printf "+----------------+------+------+\n"
printf "| %-14s | %-4s | %-4s |\n", "姓名", "年龄", "城市"
printf "+----------------+------+------+\n"
}
{
if(NR>1) {
printf "| %-14s | %-4s | %-4s |\n", $1, $2, $3
printf "+----------------+------+------+\n"
}
}
EOF
Node.js + table库
const Table = require('cli-table3');
function textToTable(text, delimiter = ',') {
const lines = text.split('\n').filter(line => line.trim());
const headers = lines[0].split(delimiter);
const table = new Table({
head: headers,
style: {
head: ['cyan'],
border: ['grey']
}
});
// 添加数据
for (let i = 1; i < lines.length; i++) {
const row = lines[i].split(delimiter);
table.push(row);
}
return table.toString();
}
// 使用
const text = `Name|Age|City
Alice|25|New York
Bob|30|London`;
console.log(textToTable(text, '|'));
通用JavaScript函数
function textToFormattedTable(text, options = {}) {
const {
delimiter = ',',
hasHeader = true,
borderStyle = 'light'
} = options;
const lines = text.trim().split('\n').map(l => l.trim()).filter(Boolean);
const rows = lines.map(line => line.split(delimiter).map(cell => cell.trim()));
// 计算列宽
const colWidths = [];
rows.forEach(row => {
row.forEach((cell, idx) => {
colWidths[idx] = Math.max(colWidths[idx] || 0, cell.length);
});
});
// 生成表格
const border = borderStyle === 'light' ?
{ h: '-', v: '|', c: '+' } :
{ h: '═', v: '║', c: '╬' };
const formatRow = (row, isHeader) => {
const cells = row.map((cell, idx) =>
` ${cell.padEnd(colWidths[idx])} `
).join(border.v);
return `${border.v}${cells}${border.v}`;
};
const separator = `+${colWidths.map(w => ''.padEnd(w + 2, border.h)).join(border.c)}+`;
// 构建表格
let result = [separator];
const dataStart = hasHeader ? 1 : 0;
// 表头
if (hasHeader) {
result.push(formatRow(rows[0], true));
result.push(separator.replace(/-/g, '='));
}
// 数据行
for (let i = dataStart; i < rows.length; i++) {
result.push(formatRow(rows[i]));
result.push(separator);
}
return result.join('\n');
}
// 使用
const text = "姓名,年龄,城市\n张三,25,北京\n李四,30,上海";
console.log(textToFormattedTable(text));
快速使用示例
将下面的文本保存为 text_to_table.py:
#!/usr/bin/env python3
import sys
def main():
if len(sys.argv) < 2:
print("用法: python text_to_table.py '文本内容'")
return
text = sys.argv[1]
lines = text.split('\n')
if len(lines) < 2:
print("需要至少两行数据(表头+数据)")
return
# 检测分隔符
if ',' in lines[0]:
sep = ','
elif '|' in lines[0]:
sep = '|'
else:
sep = '\t'
# 提取表头和数据
headers = lines[0].split(sep)
data = [line.split(sep) for line in lines[1:]]
# 计算列宽
col_widths = [len(h) for h in headers]
for row in data:
for i, cell in enumerate(row):
col_widths[i] = max(col_widths[i], len(cell))
# 输出表格
def format_row(row):
return '| ' + ' | '.join(
cell.ljust(width) for cell, width in zip(row, col_widths)
) + ' |'
separator = '+' + '+'.join('-' * (w + 2) for w in col_widths) + '+'
print(separator)
print(format_row(headers))
print(separator.replace('-', '='))
for row in data:
print(format_row(row))
print(separator)
if __name__ == '__main__':
main()
这些方法都可以将文本快速转换为格式化的表格,选择哪种方法取决于你的具体需求和使用环境。