簡體   English   中英

使用PYCOUNTRY將ISO 3166-1 alpha-2轉換為國家名稱

[英]Use PYCOUNTRY to convert ISO 3166-1 alpha-2 to Country Name

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

感謝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")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM