UnicodeEncodeError:“ascii”编码解码器不能以特殊名称编码字符[复制]

时间:2022-06-12 20:19:49

This question already has an answer here:

这个问题已经有了答案:

My python (ver 2.7) script is running well to get some company name from local html files but when it comes to some specific country name, it gives this error "UnicodeEncodeError: 'ascii' codec can't encode character"

我的python (ver 2.7)脚本运行良好,可以从本地的html文件中获取一些公司名称,但是当涉及到某个特定的国家名称时,它会给出这个错误“UnicodeEncodeError:‘ascii’编码编码不能编码字符”

Specially getting error when this company name comes

当公司名称出现时,特别容易出错。

Company Name: Kühlfix Kälteanlagen Ing.Gerhard Doczekal & Co. KG

公司名称:Kuhlfix Kalteanlagen Ing。Gerhard Doczekal & Co. KG。

The link cannot be processed

无法处理该链接。

Traceback (most recent call last): 
  File "C:\Python27\Process2.py", line 261, in <module>
    flog.write("\nCompany Name: "+str(pCompanyName))
UnicodeEncodeError: 'ascii' codec can't encode character u'\xfc' in position 9: ordinal not in range(128)

Error gives in this line of code:

在这一行代码中出现了错误:

if companyAlreadyKnown == 0:
   for hit in soup2.findAll("h1"):
       print "Company Name: "+hit.text
       pCompanyName = hit.text
       flog.write("\nCompany Name: "+str(pCompanyName))
       companyObj.setCompanyName(pCompanyName)

2 个解决方案

#1


202  

Try setting the system default encoding as utf-8 at the start of the script, so that all strings are encoded using that.

在脚本开始时,尝试将系统默认编码设置为utf-8,这样所有字符串都可以使用它进行编码。

Example -

的例子,

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

The above should set the default encoding as utf-8 .

上面应该将默认编码设置为utf-8。

#2


30  

You really want to do this

你真的想这么做。

flog.write("\nCompany Name: "+ pCompanyName.encode('utf-8'))

This is the "encode late" strategy described in this unicode presentation (slides 32 through 35).

这是在这个unicode表示中描述的“编码延迟”策略(幻灯片32到35)。

#1


202  

Try setting the system default encoding as utf-8 at the start of the script, so that all strings are encoded using that.

在脚本开始时,尝试将系统默认编码设置为utf-8,这样所有字符串都可以使用它进行编码。

Example -

的例子,

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

The above should set the default encoding as utf-8 .

上面应该将默认编码设置为utf-8。

#2


30  

You really want to do this

你真的想这么做。

flog.write("\nCompany Name: "+ pCompanyName.encode('utf-8'))

This is the "encode late" strategy described in this unicode presentation (slides 32 through 35).

这是在这个unicode表示中描述的“编码延迟”策略(幻灯片32到35)。