Skip to content

Instantly share code, notes, and snippets.

@sota1235
Created July 21, 2015 05:59
Show Gist options
  • Save sota1235/50ff502b00f1bf0e4e86 to your computer and use it in GitHub Desktop.
Save sota1235/50ff502b00f1bf0e4e86 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
# -*- cofing: utf-8 -*-
import unicodedata
import sys
# 全角含んだ文字の幅を返す
def count_word_width(word):
width = 0
for w in word:
if unicodedata.east_asian_width(w) is 'W':
width += 2
else:
width += 1
return width
# ファイル読み込み
filename = sys.argv[1]
data = []
for line in open(filename, 'r'):
data.append(line.replace('\n', '').split(','))
columns = len(data[0]) # カラム数
# それぞれのカラムの最大値を取得
max_width = []
for i in range(columns):
elm = []
for j in range(len(data)):
elm.append(count_word_width(data[j][i]))
max_width.append(max(elm))
# ファイル出力
f = open('./answer/output.txt', 'w')
for d in data:
wline = []
for i in range(columns):
wline.append(d[i] + ' ' * (max_width[i] - count_word_width(d[i])))
f.write('|' + '|'.join(wline) + '|\n')
f.close()
@sota1235
Copy link
Author

全角含めた文字幅測ってcsvを整形するプログラム(新人課題)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment