我试图建立一个RNN模型,它将评论分为积极的或消极的情绪。
这里有一个语音词典,在预处理中,我对一些索引序列进行了回顾。
例如,
“这部电影最棒”-> 2,5,10,3
当我试图获取频繁的语音并查看其内容时,我得到了以下错误:
num of reviews 100
number of unique tokens : 4761
Traceback (most recent call last):
File "preprocess.py", line 47, in <module>
print(vocab)
UnicodeEncodeError: 'ascii' codec can't encode character '\xe9' in position 10561: ordinal not in range(128)代码如下:
from bs4 import BeautifulSoup
reviews = []
for item in os.listdir('imdbdata/train/pos')[:100]:
with open("imdbdata/train/pos/"+item,'r',encoding='utf-8') as f:
sample = BeautifulSoup(f.read()).get_text()
sample = word_tokenize(sample.lower())
reviews.append(sample)
print("num of reviews", len(reviews))
word_freq = nltk.FreqDist(itertools.chain(*reviews))
print("number of unique tokens : %d"%(len(word_freq.items())))
vocab = word_freq.most_common(vocab_size-1)
index_to_word = [x[0] for x in vocab]
index_to_word.append(unknown_token)
word_to_index = dict((w,i) for i,w in enumerate(index_to_word))
print(vocab)问题是,在用Python处理NLP问题时,我如何摆脱这个UnicodeEncodeError?特别是当使用open函数获取一些文本时。
发布于 2017-10-09 10:41:17
看起来您的终端是为ASCII配置的。由于字符'\xe9'超出了ASCII字符的范围(0x00-0x7F),因此无法在ASCII终端上打印。它也不能被编码为ASCII:
>>> s = '\xe9'
>>> s.encode('ascii')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character '\xe9' in position 0: ordinal not in range(128)您可以通过在打印时显式编码字符串并通过用?替换不支持的字符来处理编码错误来解决此问题。
>>> print(s.encode('ascii', errors='replace'))
b'?'该字符看起来像是ISO-8859-1编码的一个小字母e与锐(é)。
您可以检查stdout使用的编码。在我的例子中,它是UTF-8,我没有问题打印这个字符:
>>> import sys
>>> sys.stdout.encoding
'UTF-8'
>>> print('\xe9')
é您可能会强迫Python使用不同的默认编码;有一些讨论是here,但最好的方法是使用支持UTF-8的终端。
https://stackoverflow.com/questions/46643825
复制相似问题