简体   繁体   中英

How can i decode bytes in a list in python?

i use python 2.7.8 , and i try to get the origin/root of the word using built in function called stem(param), but the list i use was in hex and when i run the program there is an error occurred. here is the code :

    from nltk.stem.isri import ISRIStemmer
    st = ISRIStemmer() 
    f=open("Hassan.txt","rU")
    text=f.read()
    text1=text.split()
    for i in range(1,numOfWords): #numOfWords is var that contain the num of 
          print st.stem(text1[i])    # words in list (text1)

and the output was as here:

    Warning (from warnings module):
    File "C:\Python27\lib\site-packages\nltk\stem\isri.py", line 154
    if token in self.stop_words:
    UnicodeWarning: Unicode equal comparison failed to convert both 
    arguments to Unicode - interpreting them as being unequal

    Traceback (most recent call last):
    File "C:\Python27\Lib\mycorpus.py", line 81, in <module>
    print st.stem(text1[i])
    File "C:\Python27\lib\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 "C:\Python27\lib\site-packages\nltk\stem\isri.py", line 198, in 
    pre32
    if word.startswith(pre3):
    UnicodeDecodeError: 'ascii' codec can't decode byte 0xc8 in position 0: 
    ordinal not in range(128)

How can i solve this problem ?!

You need to decode the text that's in your file. Assuming your file is encoded as UTF-8:

text=f.read().decode('utf-8')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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