使用 ISRIStemmer 提取文件中的阿拉伯语文本时出错

Error while stemming arabic text in file using ISRIStemmer

我正在尝试使用 nltk.stem.isri 提取阿拉伯语文本文件 (text.txt) 的内容。 text.txt 文件包含以下阿拉伯语文本:

一个人在一生中感受到的感受是多种多样的,这些感受取决于特定的情况或人,而爱情被认为是折磨人的美丽感受之一,因此它改变了他对周围世界的看法并变得更加积极,是情感关系将男人和女人或生活中不同的人联系在一起,吸引他的是兴趣、亲情和善意的感觉。爱情也是人与人之间的一种相互吸引和倾慕的状态,据说是一种相互的化学反应,表达的是人与人之间的一种互动,而在爱情中人体会分泌一种叫做催产素的激素,这种激素叫做催产素。恋人和爱情的荷尔蒙,是爱人相遇后身体立即分泌的激素,下面几行我们将详细和澄清一些关于爱情的一般信息。

参考之前的一个问题,我使用了下面的代码:Python Stemming words in a File

# -*- coding: UTF-8 -*-

from nltk.stem.isri import ISRIStemmer
def stemming_text_1():
    with open('test.txt', 'r') as f:
        for line in f:
            print line
            singles = []

            stemmer = ISRIStemmer()
            for plural in line.split():
                singles.append(stemmer.stem(plural))
            print ' '.join(singles)

stemming_text_1()

它打印文件的内容和这个错误:

/home/waheeb/anaconda2/lib/python2.7/site-packages/nltk/stem/isri.py:154:     UnicodeWarning: Unicode equal comparison failed to convert     both arguments to Unicode - interpreting them as being unequal
  if token in self.stop_words:
Traceback (most recent call last):
  File "Arabic_stem.py", line 15, in <module>
    stemming_text_1()
  File "Arabic_stem.py", line 12, in stemming_text_1
    singles.append(stemmer.stem(plural))
  File "/home/waheeb/anaconda2/lib/python2.7/site-packages/nltk/stem    /isri.py", line 156, in stem
    token = self.pre32(token)     # remove length three and length two     prefixes in this order
  File "/home/waheeb/anaconda2/lib/python2.7/site-packages/nltk/stem    /isri.py", line 198, in pre32
    if word.startswith(pre3):
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd8 in position 0:     ordinal not in range(128)

尝试将文件中的行解码为 unicode,然后再将其传递给词干分析器。我假设您的输入文件编码为 UTF8(看起来很可能是在查看错误),但是,您可以根据需要更改编码:

for line in f:
    line = line.decode('utf8')    # use the correct encoding here
    ...

或者您可以使用 io.open(),指定编码,Python 会将传入的流解码为 un​​icode:

with io.open('test.txt', encoding='utf8') as f:
    ...