繁体   English   中英

Python re.sub返回二进制字符

[英]Python re.sub returning binary characters

我正在尝试使用Python中的re.sub()regex表达式修复JSON feed。 (我也正在与供稿提供商一起对其进行修复)。 我有两个要修复的表达式:

1。

      "milepost":       "
      "milepost":       "723.46

缺少结尾引号,并且

2。

    },

}

其中不应该包含逗号。 请注意,它们之间没有空白行,只是“},\\ n}”(此编辑器有问题...)

我有一个摘要的摘要,位于: http : //hardhat.ahmct.ucdavis.edu/tmp/test.txt

下面的示例代码。 在这里,我进行了测试,以查找模式,然后进行替换。 #2的匹配给出了一些奇怪的结果,但我看不出为什么:找到括号匹配:[('}','\\ r \\ n}')]

排名第一的比赛似乎不错。

主要问题是,当我执行re.sub时,生成的字符串中包含“ \\ x01 \\ x02”。 我不知道这是从哪里来的。 任何建议,不胜感激。

样例代码:

import urllib2
import json
import re

if __name__ == "__main__":
    # wget version of real feed:
    # url = "http://hardhat.ahmct.ucdavis.edu/tmp/test.json"
    # Short text, for milepost and brace substitution test:
    url = "http://hardhat.ahmct.ucdavis.edu/tmp/test.txt"
    request = urllib2.urlopen(url)
    rawResponse = request.read()
    # print("Raw response:")
    # print(rawResponse)

    # Find extra comma after end of records:
    p1 = re.compile('(}),(\r?\n *})')
    l1 = p1.findall(rawResponse)
    print("Brace matches found:")
    print(l1)

    # Check milepost:
    #p2 = re.compile('( *\"milepost\": *\")')
    p2 = re.compile('( *\"milepost\": *\")([0-9]*\.?[0-9]*)\r?\n')
    l2 = p2.findall(rawResponse)
    print("Milepost matches found:")
    print(l2)

    # Do brace substitutions:
    subst = "\1\2"
    response = re.sub(p1, subst, rawResponse)

    # Do milepost substitutions:
    subst = "\1\2\""
    response = re.sub(p2, subst, response)
    print(response)

您需要使用原始字符串,否则Python字符串处理器会将"\\1\\2"解释为ASCII 01 ASCII 02而不是backslash 1 backslash 2

代替

subst = "\1\2"

采用

subst = r"\1\2" # or subst = "\\1\\2"

第二个替换使事情变得有些棘手:

subst = "\1\2\""

需要成为

subst = r'\1\2"' # or subst = "\\1\\2\""

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM