ãã¦ãæ¬æ¥ã¯Python 㧠XML ã CSV ã«å¤æããæ¹æ³ã«ã¤ãã¦æ¸ãã¦ã¿ããã¨æãã¾ããååã®ã¨ã³ããªã¼ã§ã¯ Python 㧠CSV ã XML ã«å¤æããæ¹æ³ã«ã¤ãã¦æ¸ãã¾ããããä»åã¯ãã®éã§ããã
使ç¨ãã XML
ååã®ã¨ã³ããªã¼ã§ä½æãã prefectures.xml ã使ç¨ãã¾ããèå³ã®ããæ¹ã¯ãã²ååã®ã¨ã³ããªã¼ãèªãã§ã¿ã¦ãã ããã
åºåãã CSV
以ä¸ã®ãããªå½¢ã§ CSV ãåºåãããã¨æãã¾ãã
å®è¡ç°å¢
Windows 10 64bit
Python 3.6.6
ãµã³ãã«ã³ã¼ã
prefectures.xml ã CSV ã«å¤æãããµã³ãã«ã§ãã
# -*- coding: utf-8 -*- import csv from xml.etree import ElementTree def xml2csv(): input_file = r"D:\data\csv\prefectures_from_xml.csv" output_file = r"D:\data\csv\prefectures.xml" # CSV ä½æ f = open(input_file, "w") # ãããã¼ output_string = "å ¬è¡¨å¹´,å ¬è¡¨æ,å ¬è¡¨æ¥,é½éåºç,æ£è æ°ï¼2020å¹´3æ28æ¥ããã¯ææè æ°ï¼,ç¾å¨ã¯å ¥é¢ç,éé¢è ,æ»äº¡è \n" # ãããã¼æ¸ã込㿠f.write(output_string) # XML èªè¾¼ tree = ElementTree.parse(output_file) # ã«ã¼ã root = tree.getroot() text_list = [] for r in root: if r.tag == "date": text_list.append(r.find('year').text) text_list.append(r.find('month').text) text_list.append(r.find('day').text) elif r.tag == "prefecture": text_list.append(r.text) elif r.tag == "info": text_list.append(r.find('cases').text) text_list.append(r.find('hospitalized').text) text_list.append(r.find('released').text) text_list.append(r.find('death').text) if len(text_list) == 8: # CSV ã«æ¸ã込㿠output_string = text_list[0] \ + "," + text_list[1] \ + "," + text_list[2] \ + "," + text_list[3] \ + "," + text_list[4] \ + "," + text_list[5] \ + "," + text_list[6] \ + "," + text_list[7] + "\n" f.write(output_string) # ãªã¹ããã¯ãªã¢ text_list = [] f.close if __name__ == '__main__': xml2csv()
çµæ
æ³å®éãã®å½¢ã§ CSV ãåºåããã¾ããã
ãããã«
ä»åã¯ããã£ã¨çµãããããã¨ãã§ãã¾ãããååã®ã¨ã³ããªã¼ã§ CSVâXMLãä»åã®ã¨ã³ããªã¼ã§XMLâCSV ã«å¤æããæ¹æ³ãç´¹ä»ãã¾ãããããã§ç¸äºå¤æãå¿ è¦ã«ãªã£ã¦ã大ä¸å¤«ãã¨æãã¾ããååã使ç¨ãã¾ããããä»åã ElementTree ã使ç¨ãã¦ãã¾ããPython 㧠XML ãæ±ãéã¯ãã使ç¨ããã©ã¤ãã©ãªãã¨æãã¾ãã®ã§ããã²è²ã 使ã£ã¦ã¿ã¦ãã ãããä»åã¯ä»¥ä¸ã§ãã