【问题标题】:Unicode errors when comparing two strings比较两个字符串时出现 Unicode 错误
【发布时间】:2014-08-26 21:01:25
【问题描述】:

我正在尝试比较两个字符串 last_contentnew_content。一个字符串是从文件中读取的,另一个是从 BeautifulSoup 传递的。当我尝试比较两者时,出现以下错误:

UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal

这就是我填充last_contentnew_content 的方式:

f = open('content.txt', 'r')
    last_content = str(f.read())

new_content = soup.find_all('div',{'class': 'threadtitleline'})[2]

这是引发错误的条件:

if new_content == last_content:
        do something awesome
    else:
        do something even more awesome

有没有办法对这些字符串进行编码以避免此错误?

【问题讨论】:

  • 你为什么在f.read()上打电话给str()?将其更改为输入str,而不是unicode...
  • 这就是我使用的示例解释它的方式。我也试过删除它,但仍然得到同样的错误。

标签: python-2.7 beautifulsoup


【解决方案1】:
with io.open('content.txt', 'r', encoding='utf-8') as f:
  last_content = f.read()

写出来的时候别忘了做同样的事情。

Unicode in Python, Completely Demystified

【讨论】:

  • 感谢您的回复,效果很好!您提供的链接也很有帮助。再次感谢您!
猜你喜欢
  • 1970-01-01
  • 2012-03-23
  • 1970-01-01
  • 1970-01-01
  • 2011-10-14
  • 1970-01-01
  • 2013-11-13
  • 2012-06-04
相关资源
最近更新 更多