python json表格化輸出
需求
- 將json數據以表格形式輸出
- 超長文本換行輸出
- 能顯示中文
- 在linux終端輸出
實現
首先數據的模樣。既然是表格化輸出,那必然傳入的數據是一個數組(廢話),如果一個項文本很長需要換行輸出,那這個項所屬的項組都要換行輸出。
首先是處理json數據:
jd = json.loads(data)
這樣產生的數據是一個字典列表,即:
[{'key0': '值5', 'key1': '值5', 'key2': '值5', 'key3': '值5', 'key4': '值5'},
{'key0': '值6', 'key1': '值6', 'key2': '值6', 'key3': '值6', 'key4': '值6'},
{'key0': '值7', 'key1': '值7', 'key2': '值7', 'key3': '值7', 'key4': '值7'},
{'key0': '值8', 'key1': '值8', 'key2': '值8', 'key3': '值8', 'key4': '值8'},
{'key0': '值9', 'key1': '值9', 'key2': '值9', 'key3': '值9', 'key4': '值9'}]
定義函數
def tabular_print(datum):
上面說了,咱們先對傳進來的數據進行檢查:
try:
if len(datum) == 0:
print('None.')
return
except TypeError:
print('None')
return
對于每個數據組,統一調用 limit_print(line) 函數來打印。
首先打印表頭:
limit_print(keys)
然后打印數據
for item in datum:
val = []
for k in keys:
val.append(item[k])
limit_print(val)
以下是 limit_print 的實現,僅針對一個漢字是兩倍字母寬度的情況。
# 在有限的寬度下進行輸出,超長則換行
def limit_print(line):
flag = True
max_row_size = 20
cnt = 0
length = []
for s in line:
length.append(get_length(str(s)))
lst = [0 for _ in range(len(line))]
sz = [0 for _ in range(len(line))]
while flag:
sod = 0
for i in range(len(line)):
s = str(line[i])
n = length[i]
if n < max_row_size * cnt:
sod += 1
print(' ' * max_row_size, end='')
else:
if n > max_row_size * (cnt + 1):
lst[i], sz[i] = next_station(s, lst[i], sz[i], max_row_size * (cnt + 1))
print(' ' * (max_row_size * (cnt + 1) - sz[i]), end='')
else:
sod += 1
lst[i], sz[i] = next_station(s, lst[i], sz[i], n)
print(' ' * (max_row_size * (cnt + 1) - sz[i]), end='')
print(' ', end='')
if sod == len(line):
flag = False
cnt += 1
print()
print('-' * (max_row_size + 1) * len(line))
# 獲取字符串在屏幕上顯示的長度
def get_length(s) -> int:
res = 0
for i in s:
# 中文占兩個單位寬度
if is_full_width(i):
res += 2
else:
res += 1
return res
# 確定換行位置
def next_station(s, idx, st, ed) -> (int, int):
while idx < len(s) and st < ed:
if is_full_width(s[idx]):
if st + 2 > ed:
return idx, st
else:
st += 2
else:
st += 1
print(s[idx], end='')
idx += 1
return idx, st
# 是否是全角符號
def is_full_width(s) -> bool:
if '\u4e00' <= s <= '\u9fa5':
return True
if '\u0f01' <= s <= '\uff60':
return True
if '\uffe0' <= s <= '\uffe6':
return True
return False

浙公網安備 33010602011771號