Python函数将国际化域名从U-Label转换为A-Label?

时间:2015-07-17 00:37:40

标签: python unicode internationalization

是否有Python函数将U标签域名转换为A标签域名?

我编码了这个,但我不确定它是否正确:

def ulabel_to_alabel(ulabel):
   for ch in ["\u3002","\uff0e","\uff61"]:
       ulabel = ulabel.replace(ch,".")
   labels = [encodings.idna.ToASCII(label) for label in ulabel.split(".")]
   return ".".join(labels)

仅调用encodings.idna.ToASCII(label)的问题在于它无法正确处理句点,并且不会保留不需要转换的标签部分。

例如:

>>> print(ulabel_to_alabel(u"matías.eu"))
xn--matas-1sa.eu
>>> print(encodings.idna.ToASCII(u"matías.eu"))
xn--matas.eu-e2a

0 个答案:

没有答案