0
Python (및 코딩 초보자)은 여기에 있습니다. 디렉토리에있는 파일 목록을 기반으로 XML 파일을 생성하려고합니다. 파일 이름의 처음 두 글자는 새 문자 국가 코드에 해당하며이 글자도 추출하려고합니다.PYCOUNTRY를 사용하여 ISO 3166-1 alpha-2를 국가 이름으로 변환하십시오.
<ROOT>
<BASIC/>
<FULL>
<INFO>
<server>filname</server>
<country>country</country>
<region/>
</INFO>
</FULL>
</ROOT>
내가 XML 파일을 생성 할 수있을 것하지만 난 pycountry를 사용하는 국가에 두 자리 국가 코드를 변환 할 수 없어요 다음과 같이
내 의도 된 형식입니다. 누군가 가능한 해결책을 제안 해 주시겠습니까? 나머지 코드에 대한 주석도 도움이 될 것입니다.
# -*- coding: utf-8 -*-
import lxml.etree as xml
import pycountry
import glob
import gettext
gettext.bindtextdomain('iso3166', pycountry.LOCALES_DIR)
_c = lambda t: gettext.dgettext('iso3166', t)
def createXML(outfile):
root = xml.Element("ROOT")
basic = xml.Element("BASIC")
full = xml.Element("FULL")
root.append(basic)
root.append(full)
# add file information
for filename in glob.glob("*.*"):
info = xml.Element("INFO")
server = xml.SubElement(info, "server")
server.text = filename
short = filename[:2]
country = xml.SubElement(info, "country")
def get_country(code):
return _c(pycountry.countries.get(alpha2=code).name)
country.text = get_country(short)
region = xml.SubElement(info, "region")
full.append(info)
print xml.tostring(root, pretty_print=True)
#save new XML
# tree = xml.ElementTree(root)
# with open(filename, "w") as fh:
# tree.write(fh)
#--------------------------------------------------------
if __name__ == "__main__":
createXML("info.xml")
1 - for 루프 내에 get_country를 정의하지 마십시오. 2 - 파일이 대문자 또는 소문자로 시작합니까? – gbe
1 - 알았습니다. 나는 그것을 밖에서 정의 할 것입니다. 함수의 결과로 텍스트를 정의하려고 시도 할 때 문제가 발생하여이를 허용하지 않습니다. 어떤 제안? 2 - 소문자이지만 가능한 한 완벽 해지고 싶습니다. 도와 주셔서 감사합니다! – RMcLellan
1에 관해서, 나는 당신이 왜 "당신을 못하게 할 것"이라고 말하는지 이해하지 못합니다. 왜 "텍스트"를 말하는지 의미하지 않습니다. – gbe