åPythonããã°ã©ã ãcsvãjsonã«å¤æ
Pythonã«ã¤ãã¦ä¸éãåºæ¬é¨åã¯åå¼·ããã¯ããªã®ã§ã¨ããããä½ãä½ã£ã¦ã¿ããã¨æãã¾ããã
ç§ã¯ããã¾ã§Javascriptããåå¼·ãããã¨ããªãã£ãã®ã§(ã¯ããæCãåå¼·ãã¾ããããã§ã«å¿ãã¦ãã¾ãã¾ãã)ããã¡ã¤ã«ã®å
¥åºåãæ±ã£ããã¨ãã»ã¨ãã©ããã¾ããã
ããã§CSVãã¡ã¤ã«ãèªã¿è¾¼ã¿JSONãã¡ã¤ã«ã«å¤æãã¦åºåããããã°ã©ã ãä½ã£ã¦ã¿ããã¨ã«ãã¾ããã
ã¾ãcsvãã¡ã¤ã«ãèªã¿è¾¼ã¿ä¸è¡ç®ã®åè¦ç´ ããã¼ãï¼è¡ç®ä»¥éã®è¦ç´ ãå¤ã¨ãããªãã¸ã§ã¯ãã®é åã«å¤æãããã¨ã«ãã¾ãã
name,age,sex ç·ã®å,20,male 女æ§,25,female
ã
[{"name": "ç·ã®å", "age": "20", "sex": "male"}, {"name": "女æ§", "age": "25", "sex": "female"}]
ã¨ãã風ã«ãªããã¨ãç®æãã¾ãã
ä»çµã¿ã¯csvãã¡ã¤ã«å ¨ä½ãï¼æ¬¡å ãªã¹ãåãã¦ããè¾æ¸ã®ãªã¹ããä½è£½ãããããjsonã¢ã¸ã¥ã¼ã«ã使ã£ã¦åºåãããã¨ã«ãã¾ãã
ããã¦æ°æéã®è©¦è¡é¯èª¤ã®æ«ã«æ¸ããã®ãããã§ãã
# coding: shift_jis #CSVãèªã¿è¾¼ãã§JSONåãã import json import codecs csvFileName = "test.csv" #èªã¿åºãã§éã csvFile = open(csvFileName,'r') #è¡ã®ãªã¹ããä½æ eachLine = [] for line in csvFile: eachLine.append(line) #ãã¡ã¤ã«éãã csvFile.close() eachPart = [""] * len(eachLine) #åè¡ãã«ã³ãã§åå² for i in range(len(eachLine)): eachPart[i] = eachLine[i].split(',') #ãã¼ã®ãªã¹ã keyList = eachPart.pop(0) #è¾æ¸ã®ãªã¹ããä½ã eachDict = [""] * len(eachPart) for i in range(len(eachPart)): eachDict[i] = {} for j in range(len(keyList)): eachDict[i][keyList[j]] = unicode(eachPart[i][j] , "shift_jis") #æ¸ããããã¡ã¤ã«ä½è£½ jsonFile = codecs.open("test.json","w","utf-8") #JSONåºå json.dump(eachDict, jsonFile, sort_keys=False, ensure_ascii=False)
å®è¡çµæã¯
[{"age": "20", "name": "ç·ã®å", "sex\n": "male\n"}, {"age": "25", "name": "女æ§", "sex\n": "female"}]
æ¹è¡ã³ã¼ãé¤å»ããã®å¿ãã¦ãã»ã»ã»ã
å
¥åãã·ããJISã«ãã対å¿ãã¦ããªãã®ã§ãããã¨ããããããã¯ä»æ§ã¨ãããã¨ã«ãã¾ãã
å½åcsvã¢ã¸ã¥ã¼ã«ã使ããã¨æã£ãã®ã§ããã«ã³ãã§åºåãã ããªããã¾ãã¡ãªãããæããããªãã£ãã®ã§split(',')ã§åã£ã¦ãã¾ãã
for i in range(len(LIST))
ã¨ããæ¸ãæ¹ããããå¤ç¨ãã¦ããã®ã¯Javascriptã®
for(var i = 0; i < array.length; i++){}
ã¨ããæ¸ãæ¹ã®ã¯ã»ã§ãã®ããæ¹ããæµ®ãã°ãªãã£ãããã§ã(^_^;)
(1/30追è¨ãããã¯Pythonã§ã¯enumerate()を使うのが普通ã®ããã§ãã)
åæ§ã«ã¯ã»ã§ã¤ã
list = [] list[0] = "hoge"
ã¨ããããããªã£ã¦ãã¾ãã¾ãããããããªã¹ãã®åæåã®ããæ¹ãããããã¨ã¯æãã¾ããããããåå¼·ãããã¨æãã¾ãã
ä¸çªæ©ãã ã®ãåºåãã¡ã¤ã«ã®æååãã§"json.dump"ã®"ensure_ascii=False"ã¨æ¸ãã°ã¨ããããæ£ããåºåã§ãããã¨ã¯åãã£ãããã©æå³ã¯ããåãã£ã¦ãã¾ããã
ãã¨ä½ãæå®ããªãå ´åè¾æ¸ã¯keyãã½ã¼ãããã¦ãã¾ãããã§ããå
ã®é çªãç¶æããããã«ãããã¨ããã§ãã
以ä¸ããã®ã³ã¼ãã®ä¸»ãªå 容ã¨èª²é¡ã§ãã
ãã°ããã¯ãã®ã³ã¼ããæ¹å¤ãã¤ã¤åå¼·ãã¦çãããã¨æãã¾ãã