如何用tabulate或其他表格格式化工具正确打印fruit.txt为表格?
解决tabulate拆分字符显示的问题
嘿,我明白你为啥会看到字符被拆成单个字母显示了——你传给tabulate的是一个字符串,而不是它需要的二维列表结构!tabulate会把字符串当成可迭代的字符序列,自然就把每个字符当成一行的第一个元素了。
咱们来一步步修正代码:
问题根源
你原来的代码里,print tabulate("{}".format(line.strip()), headers=['Veggie', 'Fruit'])这一行,把每行内容转成了字符串直接传进去,tabulate就会把这个字符串拆成单个字符来渲染,所以才会出现Veggie列显示c、o、r、n这种情况。
修正后的代码(适配每行一个条目的fruit.txt)
假设你的fruit.txt是每行存一组蔬菜和水果,格式如下:
corn, apple
lettuce, grapes
pepper, melon
那可以这样写代码:
from tabulate import tabulate filepath = 'fruit.txt' table_rows = [] # 先收集所有行的数据,再统一生成表格 with open(filepath) as fp: for line in fp: # 去掉行首尾的空白(包括换行符) cleaned_line = line.strip() if not cleaned_line: continue # 跳过空行 # 按逗号分割,再去掉每个元素的空格 veggie, fruit = [item.strip() for item in cleaned_line.split(',')] table_rows.append([veggie, fruit]) # 生成并打印表格,tablefmt可选,比如'grid'、'plain'、'pretty'等 print(tabulate(table_rows, headers=['Veggie', 'Fruit'], tablefmt='grid'))
如果fruit.txt是一行用中文分号分隔所有条目
要是你的fruit.txt内容是一行写所有条目:corn, apple;lettuce, grapes;pepper, melon,那只需要调整读取和分割的逻辑:
from tabulate import tabulate filepath = 'fruit.txt' table_rows = [] with open(filepath) as fp: # 读取整个文件内容 content = fp.read().strip() # 按中文分号分割所有条目 items = content.split(';') for item in items: cleaned_item = item.strip() if not cleaned_item: continue veggie, fruit = [part.strip() for part in cleaned_item.split(',')] table_rows.append([veggie, fruit]) print(tabulate(table_rows, headers=['Veggie', 'Fruit'], tablefmt='pretty'))
关键要点
- 给
tabulate传数据时,必须是二维列表(或者元组的列表),每个子列表对应表格的一行 - 分割字符串后记得用
strip()去掉多余空格,避免表格里出现不必要的空白 - 建议先收集所有数据再一次性生成表格,这样输出是一个完整的表格,而不是逐行打印多个小表格
内容的提问来源于stack exchange,提问作者Benjamin Jones
相关产品推荐
相关产品推荐

