【问题标题】:UnicodeEncodeError: 'ascii' codec can't encode characters in position 7-9: ordinal not in range(128)UnicodeEncodeError:“ascii”编解码器无法对位置 7-9 中的字符进行编码:序数不在范围内(128)
【发布时间】:2015-09-26 17:28:22
【问题描述】:

我一直在开发一个程序来浏览我已经保存在文本文件中的各种链接,这些链接主要是夏季机会/营地/等。并刮擦它们,看看是否弹出诸如“奖学金”或“经济援助”之类的关键词。但是,当我运行它时,它给了我上面标题中的错误。

这个问题已经被问过好几次了,但对于不同的人来说似乎是出于不同的原因。因此,我知道可能存在涉及 Unicode 的错误,但我不知道会出现在哪里或为什么会这样。

这是代码:

import BeautifulSoup
import requests
import nltk

file_from = open("links.txt", "r")
list_of_urls = file_from.read().splitlines()

aid_words = ["financial", "aid", "merit", "scholarship"]

count = 0

fin_aid = []

while count <= 10:
    for url in list_of_urls:
        clean = 1
        result = "nothing found"
        source = requests.get(url)
        plain_text = source.text
        soup = BeautifulSoup.BeautifulSoup(plain_text)
        print (str(url).upper())
        for links in soup.findAll('p', text = True):
            tokenized_text = nltk.word_tokenize(links)
            for word in tokenized_text:
                if word not in aid_words:
                    print ("not it " + str(clean))
                    clean += 1
                    pass
                else:
                    result = str(word)
                    print (result)
                    fin_aid.append(url)
                    break
    count += 1
    the_golden_book = {"link: ": str(url), "word found: ": str(result)}
    fin_aid.append(the_golden_book)

file_to = open("links_with_aid.txt", "w")
file_to.write(str(fin_aid))
file_to.close()

print ("scrape finished")
print (str(fin_aid))

基本上是想从links.txt中取出所有链接,访问前十个(作为测试),在列表“aid_words”中搜索四个单词,以“not it”的形式返回结果以及到目前为止搜索的单词数,如果还没有找到单词,或者如果找到了则检测到的单词(以便我稍后可以访问链接并搜索它,看看它是否是一个误报与否)。

当我通过命令提示符运行它时,这是它在错误消息之前向我显示的内容。

Traceback (most recent call last):
  File "finaid.py", line 20, in <module>
    soup = BeautifulSoup.BeautifulSoup(plain_text.encode("utf-8"))
  File "C:\Python27\lib\site-packages\BeautifulSoup.py", line 1522, in __init__
    BeautifulStoneSoup.__init__(self, *args, **kwargs)
  File "C:\Python27\lib\site-packages\BeautifulSoup.py", line 1147, in __init__
    self._feed(isHTML=isHTML)
  File "C:\Python27\lib\site-packages\BeautifulSoup.py", line 1189, in _feed
    SGMLParser.feed(self, markup)
  File "C:\Python27\lib\sgmllib.py", line 104, in feed
    self.goahead(0)
  File "C:\Python27\lib\sgmllib.py", line 143, in goahead
    k = self.parse_endtag(i)
  File "C:\Python27\lib\sgmllib.py", line 320, in parse_endtag
    self.finish_endtag(tag)
  File "C:\Python27\lib\sgmllib.py", line 358, in finish_endtag
    method = getattr(self, 'end_' + tag)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 7-9: ordin
al not in range(128)

我在 Python 2.7.10 上运行它,我在 Windows 8.1 上。感谢您的任何帮助,您可以提供!据我所知,它不应该是“link.txt”中的任何内容,这实际上只是同事之前抓取并保存的链接。

【问题讨论】:

  • 1.代码和回溯不匹配。显示对应于实际代码的回溯。 2. 不要转储所有代码,创建一个minimal (but complete) code example instead 3. 不相关:在这种情况下避免str() -- 你的用法要么是错误,要么有更好的替代方案。
  • 短答案:使用python3,长答案:使用文本5年我仍然在python2.x,用户python3中遇到问题
  • 当我在 Python 3 上运行它(进行了所有必要的调整)时,它给出了“预期的字符串或缓冲区”,我觉得这更令人困惑。它给出了我使用“word_tokenize”的行的错误。我对 BeautifulSoup 和 nltk 比其他东西更熟悉——有没有办法在不使用这两个的情况下解决这个错误?
  • @alvas:Python 3 可以很容易地检测到一些 Unicode 问题,但它不是小精灵。除非 OP 将学习如何使用 Unicode(第一步:删除可疑的 str() 用法);问题不会飞到梦幻岛。

标签: python python-2.7 unicode beautifulsoup nltk


【解决方案1】:

我做了很多网站抓取,我可以告诉您:请尝试使用 Python 3 编写您的抓取器代码。一旦我将抓取器更新为使用 Python 3,我的很多编码问题就消失了。如果您确实使用 Python 3 并且希望保持该文件的内容完整,请确保在您的文件写入时使用“a”而不是“w”。

如果您对过渡有任何具体问题,请告诉我。

在“预期的字符串或缓冲区”上,当我传入对象而不是字符串时,通常会向我显示。要检查这种情况,请使用 print 语句进行检查,如下所示:

for links in soup.findAll('p', text = True):
    print(links)
    tokenized_text = nltk.word_tokenize(links)

如果它没有将文本打印到您的终端(或您运行脚本的任何地方),那么当它期望接收字符串时,您正在传递一个对象。

修复它的伪代码可能如下所示:

for links in soup.findAll('p', text = True):
    links = links.text()
    tokenized_text = nltk.word_tokenize(links)

【讨论】:

  • 我的电脑上实际上有 3.4。我试用了 2.7,因为我们已经在其他几台笔记本电脑上运行了 Ubuntu,但只有 2.7,而我的一位同事的 Mac 默认使用 2.7。我最初是在 3.4 中编写的,但它给出了一个不同的错误:“预期的字符串或缓冲区”。我也查过了,但我也不知道这如何适用于我的帖子。
  • 我可能会犯这个错误,但你不能做这样的事情并一起绕过使用 nltk 吗?我没有使用过那个模块,所以我承认我对它不太熟悉.. pastebin.com/cvHKfer0(我不知道如何在对答案的评论中发布代码:(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-05
  • 2020-07-27
  • 2012-07-17
  • 2018-04-28
  • 2014-03-08
  • 2017-02-28
相关资源
最近更新 更多