【问题标题】:UnicodeDecodeError, ascii processing for Snowball stemming algorithm in pythonUnicodeDecodeError,python 中雪球词干算法的 ascii 处理
【发布时间】:2012-06-10 14:38:54
【问题描述】:

我在将一般文件读入我制作的程序时遇到了一些麻烦。我目前遇到的问题是 pdf 基于某种变异的 utf-8,包括一个 BOM,它给我的整个操作带来了麻烦。在我的应用程序中,我使用需要 ascii 输入的 Snowball 词干算法。有许多主题涉及解决 utf-8 的错误,但是没有一个涉及将它们发送到 Snowball 算法中,或者考虑 ascii 是我想要的最终结果这一事实。目前我使用的文件是使用标准 ANSI 编码的记事本文件。我得到的具体错误信息是这样的:

File "C:\Users\svictoroff\Desktop\Alleyoop\Python_Scripts\Keywords.py", line 38, in Map_Sentence_To_Keywords
    Word = Word.encode('ascii', 'ignore')
UnicodeDecodeError: 'ascii' codec can't decode byte 0x96 in position 0: ordinal not in range(128)

我的理解是,在 python 中,包括忽略参数会简单地传递遇到的任何非 ascii 字符,这样我会绕过任何 BOM 或特殊字符,但显然情况并非如此。调用的实际代码在这里:

def Map_Sentence_To_Keywords(Sentence, Keywords):
    '''Takes in a sentence and a list of Keywords, returns a tuple where the
    first element is the sentence, and the second element is a set of
    all keywords appearing in the sentence. Uses Snowball algorithm'''
    Equivalence = stem.SnowballStemmer('english')
    Found = []
    Sentence = re.sub(r'^(\W*?)(.*)(\n?)$', r'\2', Sentence)
    Words = Sentence.split()
    for Word in Words:
        Word = Word.lower().strip()
        Word = Word.encode('ascii', 'ignore')
        Word = Equivalence.stem(Word)
        Found.append(Word)
    return (Sentence, Found)

通过将一般的非贪婪的非字符正则表达式删除包含到字符串的前面,我还希望删除麻烦的字符,但事实并非如此。除了 ascii 之外,我还尝试了许多其他编码,并且严格的 base64 编码有效,但对于我的应用程序来说非常不理想。有关如何以自动化方式解决此问题的任何想法?

Element 的初始解码失败,但在实际传递给编码器时返回 unicode 错误。

for Element in Curriculum_Elements:
        try:
            Element = Element.decode('utf-8-sig')
        except:
            print Element 
        Curriculum_Tuples.append(Map_Sentence_To_Keywords(Element, Keywords))

def scraping(File):
    '''Takes in txt file of curriculum, removes all newlines and returns that occur \
    after a lowercase character, then splits at all remaining newlines'''
    Curriculum_Elements = []
    Document = open(File, 'rb').read()
    Document = re.sub(r'(?<=[a-zA-Z,])\r?\n', ' ', Document)
    Curriculum_Elements = Document.split('\r\n')
    return Curriculum_Elements

显示的代码生成所见的课程元素。

 for Element in Curriculum_Elements:
        try:
            Element = unicode(Element, 'utf-8-sig', 'ignore')
        except:
            print Element 

这种类型转换的hackaround确实有效,但是转换回ascii有点不稳定。返回此错误:

Warning (from warnings module):
  File "C:\Python27\lib\encodings\utf_8_sig.py", line 19
    if input[:3] == codecs.BOM_UTF8:
UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal

【问题讨论】:

  • 你确定它应该是非贪婪的吗?假设你有^A^AHello, World!。然后,由于非贪婪,^As 中的 none 在第一次捕获中匹配。它们最终出现在第二次捕获中,因此出现在您的替换字符串中。
  • 好点,但我的问题实际上只是在字符根本无法识别的情况下。

标签: python regex encoding byte-order-mark python-unicode


【解决方案1】:

尝试先将 UTF-8 输入解码为 unicode 字符串,然后将其编码为 ASCII(忽略非 ASCII)。对已经编码的字符串进行编码真的没有意义。

input = file.read()   # Replace with your file input code...
input = input.decode('utf-8-sig')   # '-sig' handles BOM

# Now isinstance(input, unicode) is True

# ...
Sentence = Sentence.encode('ascii', 'ignore')

在编辑之后,我发现您已经尝试在将字符串编码为 ASCII 之前对其进行解码。但是,在文件的内容已经被操纵之后,似乎解码发生得太晚了。这可能会导致问题,因为并非每个 UTF-8 字节都是一个字符(某些字符需要几个字节来编码)。想象一下将任何字符串转换为as 和bs 序列的编码。您不想在解码之前对其进行操作,因为即使未编码的字符串中没有任何内容,您也会在任何地方看到as 和bs——尽管UTF-8 也会出现同样的问题更巧妙的是,因为 大多数 字节确实是字符。

所以,先解码一次,然后再执行其他任何操作:

def scraping(File):
    '''Takes in txt file of curriculum, removes all newlines and returns that occur \
    after a lowercase character, then splits at all remaining newlines'''
    Curriculum_Elements = []
    Document = open(File, 'rb').read().decode('utf-8-sig')
    Document = re.sub(r'(?<=[a-zA-Z,])\r?\n', ' ', Document)
    Curriculum_Elements = Document.split('\r\n')
    return Curriculum_Elements

# ...

for Element in Curriculum_Elements:
    Curriculum_Tuples.append(Map_Sentence_To_Keywords(Element, Keywords))

您的原始 Map_Sentence_To_Keywords 函数无需修改即可工作,但我建议在拆分之前将其编码为 ASCII,以提高效率/可读性。

【讨论】:

  • 句子在被传递给这个函数之前已经被解码了。
  • so Sentence 是unicode 的一个实例?如果是这样,你不应该得到那个错误。也许在你的函数顶部添加一个assert isinstance(Sentence, unicode) 来仔细检查?
  • 解码由于某种原因无法正常工作,将编辑以将相关代码添加到此错误。
  • @Slater:嗯,Curriculum_Elements 是从哪里来的?一般来说,您应该在操作之前将文件作为一个整体解码,因为 UTF-8 可以包含您不想意外拆分的多字节编码(在您的情况下肯定会包含)。
  • 我能够使用上面显示的类型转换进行解码,但是当需要将其编码回 ascii 时,它有一些 bom 问题,将发布新的错误消息。
猜你喜欢
  • 2018-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多