【问题标题】:Convert `\195\164` to `u'\xc4'` - result from DNS resolver back to unicode将 `\195\164` 转换为 `u'\xc4'` - 从 DNS 解析器返回到 unicode
【发布时间】:2018-03-20 17:27:16
【问题描述】:

对 unicode-hostname 进行 DNS 解析会返回以下内容:

'\195\164\195\182\195\188o.mydomain104.local.'

\195\164 实际上是以下 unicode 字母:Ä (u'\xc4')。

原来的主机名是:

ÄÖÜO.mydomain104.local

我正在寻找一种方法将其转换回 unicode 字符串(在 python2.7 中)

如果需要原始代码,如下所示:

from dns import resolver, reversename
from dns.exception import DNSException

def get_name(ip_address):
    answer = None
    res = resolver.Resolver()
    addr = reversename.from_address(ip_address)
    try:
        answer = res.query(addr, "PTR")[0].to_text().decode("utf-8")
    except DNSException:
        pass
    return answer

我查看了.encode.decodeunicodedata 库和codecs,但没有发现任何有用的东西。

【问题讨论】:

  • 这不是一个有效的 DNS 名称,DNS 中的国际字母必须用 punycode (xn--...) 编码。那么您是如何检索这些数据的呢?
  • @KlausD。感谢您的回复,添加了那里使用的python代码...
  • 请发布repr(get_name(ip_address)),以便我们确切知道我们正在处理的str

标签: python python-2.7 unicode encoding character-encoding


【解决方案1】:

线索#1:

In [1]: print(b'\xc3\xa4\xc3\xb6\xc3\xbc'.decode('utf_8'))
äöü 

In [2]: print(bytearray([195,164,195,182,195,188]).decode('utf-8'))
'äöü'

线索#2:根据the docs,Python 将\ooo 解释为具有八进制值ooo 的ASCII 字符,并将\xhh 解释为具有十六进制值hh 的ASCII 字符。

由于 9 不是有效的八进制数,'\195' 被解释为 '\1''95'

hex(195)'0xc3'。所以我们想要'\xc3',而不是'\195'。 我们需要将每个反斜杠后面的小数转换成\xhh的形式。


在 Python2 中:

import re

given = r'\195\164\195\182\195\188o.mydomain104.local.'
# print(list(given))
decimals_to_hex = re.sub(r'\\(\d+)', lambda match: '\\x{:x}'.format(int(match.group(1))), given)
# print(list(decimals_to_hex))
result = decimals_to_hex.decode('string_escape')
print(result)

打印

äöüo.mydomain104.local.

在 Python3 中,使用 codecs.escape_decode 代替 decode('string_escape')

import re
import codecs

given = rb'\195\164\195\182\195\188o.mydomain104.local.'

decimals_to_hex = re.sub(rb'\\(\d+)',
    lambda match: ('\\x{:x}'.format(int(match.group(1)))).encode('ascii'), given)
print(codecs.escape_decode(decimals_to_hex)[0].decode('utf-8'))

打印相同的结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-19
    • 1970-01-01
    • 2017-09-26
    • 2016-11-04
    • 2021-03-12
    相关资源
    最近更新 更多