【问题标题】:Python Unicode error, 'ascii' codec can't encode characterPython Unicode 错误,“ascii”编解码器无法编码字符
【发布时间】:2015-02-03 13:10:00
【问题描述】:

我收到以下错误:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe1' in position 587: ordinal not in range(128)

我的代码:

import os
from bs4 import BeautifulSoup

do = dir_with_original_files = 'C:\Users\Me\Directory'
dm = dir_with_modified_files = 'C:\Users\Me\Directory\New'
for root, dirs, files in os.walk(do):
    for f in files:
        if f.endswith('~'): #you don't want to process backups
            continue
        original_file = os.path.join(root, f)
        mf = f.split('.')
        mf = ''.join(mf[:-1])+'_mod.'+mf[-1] # you can keep the same name 
                                             # if you omit the last two lines.
                                             # They are in separate directories
                                             # anyway. In that case, mf = f
        modified_file = os.path.join(dm, mf)
        with open(original_file, 'r') as orig_f, \
             open(modified_file, 'w') as modi_f:
            soup = BeautifulSoup(orig_f.read())
            for t in soup.find_all('td', class_='test'):
                t.string.wrap(soup.new_tag('h2'))
            # This is where you create your new modified file.
            modi_f.write(soup.prettify())

这段代码正在遍历一个目录,并为每个文件找到类 test 的所有 td,并将​​ h2 标记添加到 td 内的文本中。所以以前,它会是:

<td class="test"> text </td>

运行此程序后,将创建一个新文件:

<td class="test"> <h2>text</h2> </td>

或者这就是我希望它发挥作用的方式。不幸的是,目前,我收到了上述错误。我相信这是因为我正在解析一些包含重音字符的文本,并且是用西班牙语编写的,带有特殊的西班牙语字符。

我可以做些什么来解决我的问题?

【问题讨论】:

  • 能否请您提供完整回溯?这将有助于显示错误发生的位置。

标签: python html unicode beautifulsoup python-unicode


【解决方案1】:

soup.prettify() 返回一个 Unicode 字符串,但您的文件需要一个 字节字符串。 Python 尝试在这里提供帮助并自动对结果进行编码,但是您的 Unicode 字符串包含超出 ASCII 标准的代码点,因此编码失败。

您必须手动编码为不同的编解码器,或使用会自动为您执行此操作的不同文件对象类型。

在这种情况下,我将编码为 BeautifulSoup 为您检测到的原始编码

modi_f.write(soup.prettify().encode(soup.original_encoding))

soup.original_encoding 反映了 BeautifulSoup 将未修改的 HTML 解码为的内容,并且基于(如果有的话)HTML 本身声明的编码,或者基于对原始数据字节的统计分析的有根据的猜测.

【讨论】:

  • 非常感谢您对我的问题的所有答复。我现在开始掌握这个了!不幸的是,当我在这里尝试使用您的解决方案时,出现错误:modi_f.write(soup.prettify().encoding(soup.original_encoding)) AttributeError: 'unicode' object has no attribute 'encoding'
  • @SimonKiely:这是我的错,这是我的拼写错误。使用的方法是unicode.encode()
  • 感谢您的帮助 :)
猜你喜欢
  • 2016-01-04
  • 1970-01-01
  • 2019-09-01
  • 2017-03-31
  • 2016-06-19
  • 1970-01-01
  • 2019-02-03
  • 1970-01-01
  • 2018-12-11
相关资源
最近更新 更多