代码之家  ›  专栏  ›  技术社区  ›  Des Grieux

来自re包的Python 2正则表达式操作不处理utf-8符号编码

  •  0
  • Des Grieux  · 技术社区  · 8 年前

    utf-8

    oro[=]sia[=]łeś
    oszust[=]ką
    

    我的脚本首先打开文本文件,读取每一行并去掉不必要的字符。然后,我的正则表达式操作首先捕捉与指定模式匹配的单词,然后插入或调整非字母字符组的位置 [=] . 这是我脚本中的一个片段:

    # -*- coding: utf-8 -*-
    import re
    
    with open(r'...\input.txt', "rb") as input, open(r'...\output.txt', "wb") as output:
    
    for line in input:
    
        word = line.strip('\r\n')
    
        # Rule 1: ^VCV -> V[=]CV
        match = re.match('^[AEIOUYaeiouy]([bcćdfghjklłmnńprsśtwzżź]|rz|sz|cz|dz|dż|dź|ch)[aąeęioóuy].*(.*\[=\].*)*', word)
        result = match.group() if match else None
    
        if result == word:
            word = re.sub('(?<=^[AEIOUYaeiouy])(?=([bcćdfghjklłmnńprsśtwzżź]|rz|sz|cz|dz|dż|dź|ch)[aąeęioóuy])', '[=]', word)
    
         outLine = word + "\n"        
         errorList.write(outLine)
    

    对于规则环境中涉及带音调符号的非拉丁字符的输入,该规则似乎失败。例如,当上述规则1的输入为 'oszust[=]ką' , re.match.group() 将其重新编码为 'oszust[=]k\xc4' . 转换最后一个字符会更改环境并匹配以下正则表达式操作的输入。

    问题显然在于 utf-8 编码,因为脚本能够处理 oro[=]sia[=]łeś ,其中规则环境不包含带音调符号的字符,很好。已经阅读 this 我尝试将输入重新编码到 因此它符合正则表达式操作的环境,但我得到了以下错误:

    'ascii' codec can't decode byte 0xc4 in position 10: ordinal not in range(128)  
    

    为什么错误提到 ascii

    1 回复  |  直到 8 年前
        1
  •  3
  •   Mark Tolonen    8 年前

    处理Unicode字符时,请使用Unicode字符串。在程序的输入/输出边界处转换Unicode字符串。如果可能,请切换到最新的Python 3。它可以更好地处理Unicode。

    # -*- coding: utf-8 -*-
    import re
    import io
    
    with io.open('input.txt', 'r', encoding='utf8') as input, \
        io.open('output.txt', 'w', encoding='utf8') as output:
    
        for line in input:
            word = line.strip()  # this will remove all leading/trailing whitespace.
    
            # Rule 1: ^VCV -> V[=]CV
            match = re.match(u'^[AEIOUYaeiouy]([bcćdfghjklłmnńprsśtwzżź]|rz|sz|cz|dz|dż|dź|ch)[aąeęioóuy].*(.*\[=\].*)*', word)
            result = match.group() if match else None
    
            if result == word:
                word = re.sub(u'(?<=^[AEIOUYaeiouy])(?=([bcćdfghjklłmnńprsśtwzżź]|rz|sz|cz|dz|dż|dź|ch)[aąeęioóuy])', u'[=]', word)
    
            outLine = word + u'\n'        
            output.write(outLine)