郵便番号CSVの整形 on Python
- Ubuntu10.4
整形してみた。整形箇所は以下。
Python 2.6.5
#! /usr/bin/env python # coding:utf-8 import codecs import re def format_zipcode(inFile, outFile): kana = "" town = "" flg_process = False # 出力ファイルオープン fout = codecs.open(outFile, 'wb', 'utf-8') # 入力ファイルオープン fin = codecs.open(inFile, 'r', 'shift_jis') # 1行ずつ読み取り for line in fin: # 文字列を配列に変換 row = line.split(',') # 後カッコが閉じられていない箇所を抽出("(") if ((row[5].find("(") > 0) and not (row[5].find(")") > 0)) or ((row[8].find("(") > 0) and not (row[8].find(")") > 0)) : # 末尾の「"」を除去 kana = re.sub("\"$", "", row[5]) town = re.sub("\"$", "", row[8]) # 後カッコが出るまで同一レコード継続中のフラグを立てる flg_process = True continue # 前カッコが閉じられていない箇所を抽出(")") if ((row[5].find(")") > 0) and not (row[5].find("(") > 0)) or ((row[8].find(")") > 0) and not (row[8].find("(") > 0)) : # 先頭の「"」を除去 kana = kana + re.sub("^\"", "", row[5]) town = town + re.sub("^\"", "", row[8]) row[5] = kana row[8] = town #後カッコが出るまで同一レコード終了のフラグを立てる flg_process = False # 後カッコが出るまで同一レコード継続中の処理 if flg_process: # 両端の「"」を除去 kana = kana + re.sub("^\"", "", re.sub("\"$", "", row[5])) town = town + re.sub("^\"", "", re.sub("\"$", "", row[8])) continue # 不要な箇所を削除(空白に置換) row[5] = re.sub(u"イカニケイサイガナイバアイ", "", row[5]) row[8] = re.sub(u"以下に掲載がない場合", "", row[8]) # ファイル書込み fout.write(','.join(row).encode('utf-8')) ##### for debug ###### #print ",".join(row), #print row[5] if row[2] == '"0330072"' or row[2] == '"0660005"' or row[2] == '"0660000"': print ",".join(row), if __name__ == "__main__": format_zipcode("../data/ken_all.csv", "../data/out.csv")
※2010/09/24:strで処理していた箇所をUnicode処理に修正
※2010/11/16:カッコが閉じられていない箇所に、全角カッコを追加修正。京都はフリガナにカッコがついていない場所がある。