python UnicodeWarning : Unicode equal comparison. 如何解决这个错误?

标签 python unicode utf-8

喜欢herehere ,我运行这段代码:

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')使用比较。要么 wordstopwords.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/

相关文章:

string - Lua unicode,使用 string.sub() 和两字节字符

c++ - 使用 ICU 去除变音符号的代码

javascript - 从 javascript 字符串中剥离 U+10000-U+10FFFF

mysql - SQL 渲染 XML 数据时出现特殊字符乱码

python - tf.contrib.learn 快速入门 : - Changing n_classes to 2 does not work

c++ - 使用 ICU 库的 UTF-8 到 ASCII

java - 如何在Android中正确处理字符串长度和编码?

csv 文件上的 Python 多处理 EOF 错误

python - 在 Python 中将 16 个字节的随机数据转换为整数

python - 在Python数组中使用通配符?