相关疑难解决方法(0)

在Python中将Unicode字符串转换为字符串(包含额外符号)

如何将Unicode字符串(包含££等额外字符)转换为Python字符串?

python string unicode type-conversion

486
推荐指数
8
解决办法
91万
查看次数

156
推荐指数
2
解决办法
7万
查看次数

漂亮的汤和字符编码

我正在尝试使用Beautiful Soup和Python 2.6.5从具有斯堪的纳维亚字符的网站中提取文本和HTML。

html = open('page.html', 'r').read()
soup = BeautifulSoup(html)

descriptions = soup.findAll(attrs={'class' : 'description' })

for i in descriptions:
    description_html = i.a.__str__()
    description_text = i.a.text.__str__()
    description_html = description_html.replace("/subdir/", "http://www.domain.com/subdir/")
    print description_html
Run Code Online (Sandbox Code Playgroud)

但是,执行后,程序将失败,并显示以下错误消息:

Traceback (most recent call last):
    File "test01.py", line 40, in <module>
        description_text = i.a.text.__str__()
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position 19:         ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)

如果有帮助的话,输入页面似乎采用ISO-8859-1编码。我尝试使用设置正确的源编码,BeautifulSoup(html, fromEncoding="latin-1")但也无济于事。

现在是2011年,我正在努力解决一些琐碎的字符编码问题,我相信所有这一切都有一个非常简单的解决方案。

html python encoding python-2.x

4
推荐指数
1
解决办法
2472
查看次数

UnicodeEncodeError: 'ascii' 编解码器无法在打印功能中编码字符

我的公司正在使用一个数据库,我正在编写一个与该数据库交互的脚本。已经有一个脚本用于将查询放在数据库上,并基于该脚本将从数据库返回结果的查询。

我正在 unix 环境中工作,我在脚本中使用该脚本从数据库中获取一些数据,并将查询结果重定向到文件。现在,当我尝试读取此文件时,我收到一条错误消息:

UnicodeEncodeError: 'ascii' codec can't encode character '\u2013' in position 9741: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)

我知道由于文件的编码,python 无法读取文件。文件的编码不是 ascii,这就是错误出现的原因。我尝试检查文件的编码并尝试使用自己的编码读取文件。

我使用的代码是-

 os.system("Query.pl \"select title from bug where (ste='KGF-A' AND ( status = 'Not_Approved')) \">patchlet.txt")
 encoding_dict3={}
 encoding_dict3=chardet.detect(open("patchlet.txt", "rb").read())
 print(encoding_dict3)
# Open the patchlet.txt file for storing the last part of titles for latest ACF in a list
 with codecs.open("patchlet.txt",encoding='{}'.format(encoding_dict3['encoding'])) as csvFile
readCSV = csv.reader(csvFile,delimiter=":")
    for row in readCSV:
        if len(row)!=0:
            if len(row) > 1:
                j=len(row)-1
                patchlets_in_latest.append(row[j])
            elif len(row) ==1:
                patchlets_in_latest.append(row[0]) …
Run Code Online (Sandbox Code Playgroud)

python ascii character-encoding python-3.x

4
推荐指数
1
解决办法
5304
查看次数