Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python UnicodeEncodeError:&x27;ascii';编解码器可以';打印函数中的t编码字符_Python_Python 3.x_Character Encoding_Ascii - Fatal编程技术网

Python UnicodeEncodeError:&x27;ascii';编解码器可以';打印函数中的t编码字符

Python UnicodeEncodeError:&x27;ascii';编解码器可以';打印函数中的t编码字符,python,python-3.x,character-encoding,ascii,Python,Python 3.x,Character Encoding,Ascii,我的公司正在使用一个数据库,我正在编写一个与该数据库交互的脚本。已经有一个脚本用于将查询放到数据库中,并基于该查询,该脚本将从数据库返回结果 我在unix环境下工作,在脚本中使用该脚本从数据库获取一些数据,并将查询结果重定向到文件。现在,当我试图读取此文件时,我得到一个错误,即- UnicodeEncodeError: 'ascii' codec can't encode character '\u2013' in position 9741: ordinal not in range(128)

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

我在unix环境下工作,在脚本中使用该脚本从数据库获取一些数据,并将查询结果重定向到文件。现在,当我试图读取此文件时,我得到一个错误,即-

UnicodeEncodeError: 'ascii' codec can't encode character '\u2013' in position 9741: ordinal not in range(128)
我知道,由于文件的编码,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])               
patchlets_in_latest_list=[]
# calling the strip_list_noempty function for removing newline and whitespace characters
patchlets_in_latest_list=strip_list_noempty(patchlets_in_latest)
# coverting list of titles in set to remove any duplicate entry if present
patchlets_in_latest_set= set(patchlets_in_latest_list)
# Finding duplicate entries in  list
duplicates_in_latest=[k for k,v in Counter(patchlets_in_latest_list).items() if v>1]
# Printing imp info for logs
    print("list of titles of patchlets in latest list are : ")
for i in patchlets_in_latest_list:
   **print(str(i))**
print("No of patchlets in latest list are : {}".format(str(len(patchlets_in_latest_list))))
其中Query.pl是用于从数据库引入查询结果的perl脚本。我得到的“patchlet.txt”(用于存储HSD结果的文件)的编码是:

即使我为读取文件提供了相同的编码,也会出现错误

请帮助我解决这个错误

编辑: 我正在使用python3.6

EDIT2:

在输出结果时,我得到了错误,文件中有一行具有未知字符。这条线看起来像:

某些故障导致vtrace无法与某些跟踪一起使用

我使用的是gvim,在gvim中,“vtrace”看起来像“~Vvtrace”。然后我在数据库中手动检查了这个字符,字符是“–”,根据我的键盘,它既不是连字符也不是下划线。这些类型的字符造成了问题

我也在linux环境下工作

编辑3:
我添加了更多代码,可以帮助跟踪错误。此外,我还突出显示了一个“print”语句
(print(str(I))
,这是我得到错误的地方。

问题

根据问题中的信息,程序正在处理非ASCII输入数据,但无法输出非ASCII数据

具体而言,该代码:

for i in patchlets_in_latest_list:
   print(str(i))
>>> s = 'Hello \u2013 World'
>>> s
'Hello – World'
>>> handlers = ['ignore', 'replace', 'xmlcharrefreplace', 'namereplace']
>>> print(str(s))
Hello – World
>>> for h in handlers:
...     print(f'Handler: {h}:', s.encode('ascii', errors=h).decode('ascii'))
... 
Handler: ignore: Hello  World
Handler: replace: Hello ? World
Handler: xmlcharrefreplace: Hello – World
Handler: namereplace: Hello \N{EN DASH} World
导致此异常的原因:

UnicodeEncodeError:“ascii”编解码器无法对字符“\u2013”进行编码

这种行为在Python2中很常见,在Python2中,对
unicode
对象调用
str
会导致Python尝试将该对象编码为ASCII,如果该对象包含非ASCII字符,则会导致
unicodencodeerror

在Python3中,对
str
实例调用
str
不会触发任何编码。但是,在
str
上调用
print
函数将
str
编码为
sys.stdout.encoding
sys.stdout.encoding
默认为返回的值。这通常是linux用户的
LANG
环境变量

解决方案

如果我们假设您的程序没有覆盖正常的编码行为,那么应该通过确保代码由UTF-8语言环境中的Python3解释器执行来解决问题

  • 100%确定代码是由Python3解释器执行的-打印
    sys.version\u info
  • 运行脚本时,请尝试设置环境变量:
    pythonionecoding=UTF-8 python3 myscript.py
  • 使用终端中的
    locale
    命令(或
    echo$LANG
    )检查您的区域设置。如果它没有结束在<代码> UTF-8/COD>,请考虑更改它。如果您在公司计算机上,请咨询系统管理员
  • 如果您的代码在cron作业中运行,请记住cron作业通常使用“C”或“POSIX”语言环境运行,这可能使用ASCII编码,除非明确设置了语言环境。同样,如果脚本在其他用户下运行,请检查他们的区域设置
解决方法

如果改变环境不可行,您可以通过使用错误处理程序将其编码为ASCII,然后解码回
str
来解决Python中的问题

在您的特定情况下,有四个有用的错误处理程序,下面的代码演示了它们的效果:

for i in patchlets_in_latest_list:
   print(str(i))
>>> s = 'Hello \u2013 World'
>>> s
'Hello – World'
>>> handlers = ['ignore', 'replace', 'xmlcharrefreplace', 'namereplace']
>>> print(str(s))
Hello – World
>>> for h in handlers:
...     print(f'Handler: {h}:', s.encode('ascii', errors=h).decode('ascii'))
... 
Handler: ignore: Hello  World
Handler: replace: Hello ? World
Handler: xmlcharrefreplace: Hello &#8211; World
Handler: namereplace: Hello \N{EN DASH} World
“忽略”和“替换”处理程序将丢失信息-您无法判断哪个字符已被空格或问号替换

xmlcharrefreplace和namereplace处理程序不会丢失信息,但替换序列可能会降低文本的可读性

由您决定哪种折衷方案是程序输出的消费者可以接受的

如果您决定使用replace处理程序,您将如下更改代码:

for i in patchlets_in_latest_list:
    replaced = i.encode('ascii', errors='replace').decode('ascii')
    print(replaced)

无论您在何处打印可能包含非ASCII字符的数据

encoding='windows-1252'
(注意小写字母“w”)或
encoding='cp1252'
应该可以工作-请看否,两者都不工作,仍然会出现相同的错误-@snakecharmerbAre您可以共享一个,并告诉我们您正在运行的python版本是什么?还有回溯?我猜问题发生在输出结果时,而不是读取输入时。但是,如果没有一些代码和数据来重现问题,或者至少是代码和回溯,那么除了猜测之外不可能做更多的事情。在使用编解码器的
之后。open
可能只是试图将
打印到Python无法确定正确编码的地方。您好……非常感谢您提供了如此令人惊讶的解释性答案。它完全解决了这个问题…非常感谢-@snakecharmerb谢谢你!!!本文的更多关键词:Docker Python Ubuntu,“print()在iPython中无法正常工作”我不知道cron作业和服务是否以同样的方式工作。就我而言,我想要的只是