with open(fin,'r') as inFile, open(fout,'w') as outFile:
for line in inFile:
line = line.replace('."</documents', '"').replace('. ', ' ')
print(' '.join([word for word in line.lower().split() if len(word) >=3 and word not in stopwords.words('english')]), file = outFile)
我有以下错误:
**UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
print(' '.join([word for word in line.lower().split() if len(word) >=3 and word not in stopwords.words('english')]), file = outFile)**
我该如何解决这个问题?
最佳答案
word not in stopwords.words('english')
使用比较。要么 word
或 stopwords.words('english')
中的至少一个值不是 Unicode 值。
由于您正在读取文件,因此这里最有可能的候选者是 word
;对其进行解码,或使用在读取数据时对数据进行解码的文件对象:
print(' '.join([word for word in line.lower().split()
if len(word) >=3 and
word.decode('utf8') not in stopwords.words('english')]),
file = outFile)**
或
import io
with io.open(fin,'r', encoding='utf8') as inFile,\
io.open(fout,'w', encoding='utf8') as outFile:
其中 io.open()
function为您提供一个文本模式的文件对象,可根据需要进行编码或解码。
后者不太容易出错。例如,您测试 word
的长度,但您真正测试的是字节数。任何包含 ASCII 代码点范围之外的字符的单词都会导致每个字符出现多个 UTF-8 字节,因此 len(word)
与 len(word.decode('utf8'))
不一样.
关于python UnicodeWarning : Unicode equal comparison. 如何解决这个错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28023984/