【问题标题】:Output ascii file from Unicode Web Scrape in Python从 Python 中的 Unicode Web Scrape 输出 ascii 文件
【发布时间】:2013-11-23 15:05:42
【问题描述】:

我是 Python 编程新手。我在我的 Python 文件中使用以下代码:

import gethtml
import articletext
url = "http://www.thehindu.com/news/national/india-calls-for-resultoriented-steps-at-asem/article5339414.ece"
result = articletext.getArticle(url)
text_file = open("Output.txt", "w")

text_file.write(result)

text_file.close()

文件articletext.py 包含以下代码:

from bs4 import BeautifulSoup
import gethtml
def getArticleText(webtext):
    articletext = ""
    soup = BeautifulSoup(webtext)
    for tag in soup.findAll('p'):
        articletext += tag.contents[0]
    return articletext

def getArticle(url):
    htmltext = gethtml.getHtmlText(url)
    return getArticleText(htmltext)

但我收到以下错误:

UnicodeEncodeError: 'ascii' codec can't encode character u'\u201c' in position 473: ordinal not in range(128)
To print the result into the output file, what proper code should I write ?

The output `result` is text in the form of a paragraph.

【问题讨论】:

标签: python unicode


【解决方案1】:

为了处理 unicode 错误,我们需要将文本编码为 un​​icode(准确地说是 UTF-8)而不是 ascii。为了确保在出现编码错误时它不会抛出错误,我们将忽略任何我们没有映射的字符。 (也可以使用 str.encode 给出的“替换”或其他选项。See the Python docs on Unicode here.

打开文件的最佳做法是使用 Python 上下文管理器,即使出现错误也会关闭文件。我在路径中使用斜杠而不是反斜杠,以确保它在 Windows 或 Unix/Linux 中都能正常工作。

text = text.encode('UTF-8', 'ignore')
with open('/temp/Out.txt', 'w') as file:
    file.write(text)

这相当于

text = text.encode('UTF-8', 'ignore')
try:
    file = open('/temp/Out.txt', 'w')
    file.write(text)
finally:
    file.close()

但是上下文管理器不那么冗长,并且不太可能导致您在错误中间锁定文件。

【讨论】:

    【解决方案2】:
    text_filefixed = open("Output.txt", "wb")
    text_filefixed.write(bytes(result, 'UTF-8')) 
    text_filefixed.close()
    

    这应该可以,试一试。

    为什么?因为将所有内容保存为字节和 utf-8 它会忽略那些编码错误:D

    编辑 确保文件存在于同一文件夹中,否则将此代码放在导入之后,它应该自己创建文件。

    text_filefixed = open("Output.txt", "a")
    text_filefixed.close()
    

    它会创建它,什么都不保存,关闭文件...但它是自动创建的,无需人工干预。

    编辑2 请注意,这仅适用于 3.3.2,但我知道您可以使用此模块在 2.7 中实现相同的功能。一些细微的区别是(我认为)2.7 中不需要请求,但您应该检查一下。

    from urllib import request
    result = str(request.urlopen("http://www.thehindu.com/news/national/india-calls-for-resultoriented-steps-at-asem/article5339414.ece").read())
    text_filefixed = open("Output.txt", "wb")
    text_filefixed.write(bytes(result, 'UTF-8')) 
    text_filefixed.close()
    

    就像我一样,你只会在 2.7 中发现这个错误,urllib.request in Python 2.7

    【讨论】:

    • 我在尝试时遇到以下错误:Traceback (most recent call last): File "C:/Python27/crawler/main.py", line 7, in <module> text_filefixed.write(bytes(result, 'UTF-8')) TypeError: str() takes at most 1 argument (2 given)
    • 哦,您使用的是 python 2.7。我的代码在 3.3.2 中工作。可能需要适应它,而且......老实说,不知道怎么做。如果你打印,这是一个工作字符串你得到什么?也许尝试写 str(result)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-21
    • 1970-01-01
    • 2011-06-06
    相关资源
    最近更新 更多