Python Unicode错误,' ascii'编解码器无法对字符进行编码

时间:2014-12-05 11:13:50

标签: python html unicode beautifulsoup python-unicode

我收到以下错误:

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的tds,并将h2标记添加到td中的文本。以前,它应该是:

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

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

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

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

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

1 个答案:

答案 0 :(得分:1)

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

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

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

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

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