0

I use the tabulate to display some data which has Chinese characters. However the output isn't organized.

from tabulate import tabulate
data = [ ["北京理工大学", "985", 2000],
         ["清华大学", "985", 3000],
         ["大连理工大学", "985", 4000],
         ["深圳大学", "211", 2000],
         ["沈阳大学", "省本", 2000],
    ]
print(tabulate(data, tablefmt="grid"))

enter image description here

Ashechol
  • 38
  • 5
  • Just in case!, It happens because tabulate module is especially done for Command Line Interface (CLI) like Terminal (linux), cmd (windows) or Python command line (it says here: https://pypi.org/project/tabulate/), so characters like Chinese characters have a different width in GUI (IDLE of python or the IDE you are working on for example) but in CLI it appear like a "?" symbol and ALL characters in CLI have the same width, so it appear propperly in CLI but as "unknown character". – Diroallu Aug 23 '19 at 07:19

2 Answers2

2

Install wcwidth package may solve your problem. Seems that tabulate uses wcwidth to handle unicode strings.

$ pip install wcwidth
0

I tried prettyable, tabulate... module for CJK env.. They have the alignment of CJK fonts problem in ASCII output. But, one way can avoid the CJK fonts alignment problem that uses html output formation.

sample code:

import prettytable as pt

tb1=pt.PrettyTable()

tb1.padding_width = 5
tb1.field_names=[" 名稱", " 項目", " 數量", "單價", "總價"]
tb1.align[" 名稱"]="c"
tb1.align["項目"]="l"
tb1.align["數量"]="r"
tb1.align["單價"]="r"
tb1.align["總價"]="r"

for task in list1:
    tb1.add_row(task)
    
print(tb1.get_html_string())         #改寫成HTML 格式輸出, 避開中文對齊問題

enter image description here

hat
  • 781
  • 2
  • 14
  • 25
Sam Sheen
  • 21
  • 3