Tôi có một danh sách dài các tên miền mà tôi cần để tạo một số báo cáo. Danh sách này chứa một số tên miền IDN và mặc dù tôi biết cách chuyển đổi chúng trong python trên dòng lệnh:Chuyển đổi tên miền thành idn trong python
>>> domain = u"pfarmerü.com"
>>> domain
u'pfarmer\xfc.com'
>>> domain.encode("idna")
'xn--pfarmer-t2a.com'
>>>
Tôi đang cố gắng làm cho nó hoạt động với một tập lệnh nhỏ đọc dữ liệu từ tệp văn bản.
#!/usr/bin/python
import sys
infile = open(sys.argv[1])
for line in infile:
print line,
domain = unicode(line.strip())
print type(domain)
print "IDN:", domain.encode("idna")
print
tôi nhận được kết quả như sau:
$ ./idn.py ./test
pfarmer.com
<type 'unicode'>
IDN: pfarmer.com
pfarmerü.com
Traceback (most recent call last):
File "./idn.py", line 9, in <module>
domain = unicode(line.strip())
UnicodeDecodeError: 'ascii' codec can't decode byte 0xfc in position 7: ordinal not in range(128)
Tôi cũng đã cố gắng:
#!/usr/bin/python
import sys
import codecs
infile = codecs.open(sys.argv[1], "r", "utf8")
for line in infile:
print line,
domain = line.strip()
print type(domain)
print "IDN:", domain.encode("idna")
print
nào đã cho tôi:
$ ./idn.py ./test
Traceback (most recent call last):
File "./idn.py", line 8, in <module>
for line in infile:
File "/usr/lib/python2.6/codecs.py", line 679, in next
return self.reader.next()
File "/usr/lib/python2.6/codecs.py", line 610, in next
line = self.readline()
File "/usr/lib/python2.6/codecs.py", line 525, in readline
data = self.read(readsize, firstline=True)
File "/usr/lib/python2.6/codecs.py", line 472, in read
newchars, decodedbytes = self.decode(data, self.errors)
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 0-5: unsupported Unicode code range
Đây là tập tin dữ liệu thử nghiệm của tôi:
pfarmer.com
pfarmerü.com
Tôi rất ý thức về nhu cầu của mình để hiểu unicode ngay bây giờ.
Cảm ơn,
Peter