Python问题中的正则表达式。 re.sub()奇怪地工作

时间:2017-06-28 18:59:44

标签: python regex python-2.7

所以我试图使用python将文本写入Microsoft Word文档。该代码完美地工作,除非它与非ascii字符运行时。当发生这种情况时,我会受到以下错误的欢迎。

  

ValueError:所有字符串必须兼容XML:Unicode或ASCII,无NULL字节或控制字符

我试图通过使用正则表达式来拔出和替换非ascii字符来解决这个问题。 re.sub(pattern, repl, string, count=0, flags=0)似乎会起作用。这是我扔在一起的代码:

match1 = re.search(ur'ʼ', bodyHTML)
match2 = re.search(ur'ï¬', bodyHTML)
match3 = re.search(ur'fl', bodyHTML)
if match1:
    print 'Match 1'
    bodyHTML = re.sub(ur'ʼ', "'", bodyHTML)
if match3:
    print 'Match 3'
    bodyHTML = re.sub(ur'fl', 'fl', bodyHTML)
if match2:
    print 'Match 2'
    bodyHTML = re.sub(ur'ï¬', 'fi', bodyHTML)

“match1”完美无缺。只要文本中有ʼ,它就会被撇号取代。

“match2”和“match3”是一个不同的故事。这是一个例子:

  

经过短暂的徒步旅行后,我们第一次看到了博物馆

当然,这会触发来自match2的响应。但不是生产

  

经过短暂的徒步旅行,我们第一次看到了博物馆

吐出来

  

经过短暂的徒步旅行,我们第一次看到了博物馆

这种情况发生了好几次。 “有意义的”变得“有意义”等等。

我不确定为什么会这样。

我也遇到了一个问题,其中match2正在滚动来自match3的所有匹配。换句话说

  

池塘上的涟漪,玻璃墙上闪闪发光的那些涟漪

成为

  

池塘上的涟漪,玻璃墙上闪闪发光的闪闪发光

而不是

  

池塘上的涟漪,玻璃墙上反射的微光也是如此

我不确定为什么match2占主导地位,特别是因为我将match3 if语句放在match2之前,因此它会删除所有带有“ﬔ的部分,并只留下“ﬔ片段为了匹配2来清理。

至于运行代码后弹出的其他非ascii字符......我不知道。

非常感谢任何帮助。

谢谢

1 个答案:

答案 0 :(得分:0)

具体的翻译'我像这样使用chr:

def process_special_characters(result):
    '''sub out known yuck for legit stuff (smart quotes, etc.), keep track of how many changes'''
    total = 0

    result = re.subn(chr(133), chr(95), result) #strange underbar
    total += result[1]
    result = re.subn(chr(145), chr(39), result[0]) #smart quote
    total += result[1]
    result = re.subn(chr(146), chr(39), result[0]) #other smart quote
    total += result[1]
    result = re.subn(chr(150), chr(45), result[0]) #strange hyphen
    total += result[1]
    result = re.subn(chr(8212), chr(45), result[0]) #strange long hyphen
    total += result[1]
    result = re.subn(chr(160), chr(32), result[0]) #non breaking space
    total += result[1]

    return result[0], total

你可以很容易地制作一个词典,然后让关键词成为你的"来自"而值是"到"并循环它。如果它是一个简短的列表,这可以正常工作。注意,使用subn可以跟踪更改的数量。您可以随时抛弃所有逻辑,然后只使用sub,只是在我的情况下,业务方需要更改计数。

如果更容易阅读,你也可以使用这样的行:

result = re.subn(chr(133), "_", result) #strange underbar
祝你好运!如果你有更多问题我会更新评论,我会更新。