python UnicodeWarning:Unicode 相等比较。如何解决这个错误?
python UnicodeWarning: Unicode equal comparison. How to solve this error?
喜欢here and here,我运行这个代码:
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'))
不同。
喜欢here and here,我运行这个代码:
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'))
不同。