0

Python(和编码新手)在这里。我正在尝试根据目录中的文件列表生成 XML 文件。文件名的前两个字母对应一个新的字母国家代码,我也在尝试提取它。

我的预期格式如下:

<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")
4

1 回答 1

0

感谢gbe的帮助!它不漂亮,但这是有效的代码。

# -*- 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].upper()
                country = xml.SubElement(info, "country")
                country.text = pycountry.countries.get(alpha2=short).name
                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")
于 2016-11-04T04:08:37.037 回答