【问题标题】:Process decimal escape in string处理字符串中的小数转义
【发布时间】:2014-01-23 06:31:29
【问题描述】:

我有一个字符串文件,每行一个,其中非 ascii 字符已使用十进制代码点进行转义。一个示例行是:

mj\\195\\164ger

(文件中的双反斜杠与打印的完全相同)

我想处理这个字符串来产生

mjäger

。按照惯例,python 使用十六进制转义而不是十进制转义(例如,上面的字符串将被写为mj\xc3\xa4ger,python 可以解码:

>>> by=b'mj\xc3\xa4ger'
>>> by.decode('utf-8')
'mjäger'

但是,Python 不能立即识别小数转义。

我编写了一个方法,可以正确地操作字符串以产生十六进制转义,但这些转义本身是转义的。如何让 python 处理这些十六进制转义以创建最终字符串?

import re

hexconst=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"]
escapes=re.compile(r"\\[0-9]{3}")
def dec2hex(matchobj):
    dec=matchobj.group(0)
    dec=int(dec[1:])
    digit1=dec//16 #integer division
    digit2=dec%16 
    hex="\\x" + hexconst[digit1] + hexconst[digit2]
    return hex

line=r'mj\195\164ger'
print(escapes.sub(dec2hex,line)) #Outputs mj\xc3\xa4ger

将上述输出从mj\xc3\xa4ger 转换为mjäger,我缺少的最后一步是什么?谢谢!

【问题讨论】:

  • print(escapes.sub(dec2hex,line)) 给出输出 mj\xc3\xa4ger,但它在内存中存储为 mj\\xc3\\xa4ger。我将删除我的答案,它与蒂姆的相似。

标签: python python-3.x escaping


【解决方案1】:

这要容易得多。 re.sub() 可以将回调函数而不是替换字符串作为参数:

>>> import re
>>> line=r'mj\195\164ger'
>>> def replace(match):
...     return chr(int(match.group(1)))

>>> regex = re.compile(r"\\(\d{1,3})")
>>> new = regex.sub(replace, line)
>>> new
'mj\xc3\xa4ger'
>>> print new
mjäger

在 Python 3 中,字符串是 Unicode 字符串,因此如果您使用编码输入(如 UTF-8 编码内容),那么您需要使用正确的类型,即 bytes:

>>> line = rb'mj\195\164ger'
>>> regex = re.compile(rb"\\(\d{1,3})")
>>> def replace(match):
...     return int(match.group(1)).to_bytes(1, byteorder="big")

>>> new = regex.sub(replace, line)
>>> new
b'mj\xc3\xa4ger'
>>> print(new.decode("utf-8"))
mjäger

【讨论】:

  • 谢谢,蒂姆,我看到这在 Python2 中有效,但在 Python 3 中,我得到了 mjäger。似乎将两个转义分别处理为两个 latin-1 字符而不是一个 unicode 字符。有什么想法吗?
  • 哦,我忽略了 Python 3 标签。我很抱歉。我已经相应地编辑了我的答案。
  • 谢谢,蒂姆。我没有意识到正则表达式可以针对字节对象运行。这使它变得容易得多。我也愚蠢地试图避免将文件作为字节读取,但我现在已经改变了,一切都很好。再次感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-17
  • 2013-03-31
  • 2011-04-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多