相关疑难解决方法(0)

UnicodeDecodeError:'utf8'编解码器无法解码位置3131中的字节0x80:无效的起始字节

我试图使用python 2.7.12从json文件中读取twitter数据.

我使用的代码是这样的:

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

    def get_tweets_from_file(file_name):
        tweets = []
        with open(file_name, 'rw') as twitter_file:
            for line in twitter_file:
                if line != '\r\n':
                    line = line.encode('ascii', 'ignore')
                    tweet = json.loads(line)
                    if u'info' not in tweet.keys():
                        tweets.append(tweet)
    return tweets
Run Code Online (Sandbox Code Playgroud)

结果我得到了:

    Traceback (most recent call last):
      File "twitter_project.py", line 100, in <module>
        main()                  
      File "twitter_project.py", line 95, in main
        tweets = get_tweets_from_dir(src_dir, dest_dir)
      File "twitter_project.py", line 59, in get_tweets_from_dir
        new_tweets = get_tweets_from_file(file_name)
      File "twitter_project.py", line 71, in get_tweets_from_file …
Run Code Online (Sandbox Code Playgroud)

json ascii utf-8 python-2.7 python-unicode

9
推荐指数
3
解决办法
3万
查看次数

PySpark - UnicodeEncodeError:'ascii'编解码器无法编码字符

将带有外来字符(åäö)的数据框加载到Spark中,使用spark.read.csv,encoding='utf-8'并尝试执行简单的show().

>>> df.show()

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/spark/python/pyspark/sql/dataframe.py", line 287, in show
print(self._jdf.showString(n, truncate))
UnicodeEncodeError: 'ascii' codec can't encode character u'\ufffd' in position 579: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)

我认为这可能与Python本身有关但我无法理解这里提到的任何技巧如何在PySpark和show() - 函数的上下文中应用.

python python-2.7 apache-spark pyspark

8
推荐指数
2
解决办法
1万
查看次数

python3中的UnicodeEncodeError

我的一些应用程序库依赖于能够将 UTF-8 字符打印到 stdout 和 stderr。因此,这不能失败:

print('\u2122')
Run Code Online (Sandbox Code Playgroud)

在我的本地机器上它可以工作,但在我的远程服务器上它引发 UnicodeEncodeError: 'ascii' codec can't encode character '\u2122' in position 0: ordinal not in range(128)

我试过$ PYTHONIOENCODING=utf8没有明显效果。

sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())
Run Code Online (Sandbox Code Playgroud)

工作了一段时间,然后停止并最终失败 ValueError: underlying buffer has been detached

sys.getdefaultencoding()返回'utf-8', 并sys.stdout.encoding返回'ANSI_X3.4-1968'

我能做什么?我不想编辑第三方库。

python unicode locale utf-8 python-3.x

6
推荐指数
1
解决办法
2208
查看次数

Python 2.x中的字符串使用哪种编码?

在python 2.x中编码字符串的默认编码是什么?我读过有两种方法可以声明一个字符串.

string = 'this is a string'
unicode_string = u'this is a unicode string'
Run Code Online (Sandbox Code Playgroud)

第二个字符串是Unicode.第一个字符串的编码是什么?

python string encoding python-2.x python-internals

6
推荐指数
2
解决办法
998
查看次数

如何在python中解码非unicode字符?

s = 'Chocolate Moelleux-M\xe8re'当我在做的时候,我有一个字符串说:

In [14]: unicode(s)
---------------------------------------------------------------------------
UnicodeDecodeError                        Traceback (most recent call last)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe8 in position 20: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)

类似地,当我试图通过使用s.decode()它来解码它时返回相同的错误.

In [13]: s.decode()
---------------------------------------------------------------------------
UnicodeDecodeError                        Traceback (most recent call last)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe8 in position 20: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)

如何将这样的字符串解码成unicode.

python unicode

5
推荐指数
1
解决办法
5723
查看次数

从Lambda中的S3通知事件中获取非ASCII文件名

keyAWS S3通知事件中表示文件名的字段是URL转义的.

当文件名包含空格或非ASCII字符时,这很明显.

例如,我已将以下文件名上传到S3:

my file ??????.txt
Run Code Online (Sandbox Code Playgroud)

通知收到:

{ 
  "Records": [
    "s3": {
        "object": {
            "key": u"my+file+%C5%99%C4%9B%C4%85%CE%BB%CE%BB%CF%85.txt"
        }
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

我试过解码使用:

key = urllib.unquote_plus(event['Records'][0]['s3']['object']['key']).decode('utf-8')
Run Code Online (Sandbox Code Playgroud)

但是产量:

my file ÅÄÄλλÏ.txt
Run Code Online (Sandbox Code Playgroud)

当然,当我尝试使用Boto从S3获取文件时,我收到404错误.

utf-8 amazon-s3 python-2.7 python-unicode aws-lambda

5
推荐指数
2
解决办法
2468
查看次数

python 2和3中的UTF-8字符串

以下代码适用于Python 3:

people = [u'Nicholas Gyeney', u'Andr\xe9']
writers = ", ".join(people)
print(writers)
print("Writers: {}".format(writers))
Run Code Online (Sandbox Code Playgroud)

并产生以下输出:

Nicholas Gyeney, André  
Writers: Nicholas Gyeney, André
Run Code Online (Sandbox Code Playgroud)

但是,在Python 2.7中,我收到以下错误:

Traceback (most recent call last):
  File "python", line 4, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' 
in position 21: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)

我可以通过更改", ".join(people)为修复此错误", ".join(people).encode('utf-8'),但如果我这样做,Python 3中的输出将更改为:

b'Nicholas Gyeney, Andr\xc3\xa9'  
Writers: b'Nicholas Gyeney, Andr\xc3\xa9'
Run Code Online (Sandbox Code Playgroud)

所以我尝试使用以下代码:

if sys.version_info < (3, 0):
    reload(sys)
    sys.setdefaultencoding('utf-8')

people = [u'Nicholas Gyeney', u'Andr\xe9']
writers = ", …
Run Code Online (Sandbox Code Playgroud)

python string utf-8 python-2.7 python-3.x

5
推荐指数
1
解决办法
1万
查看次数

Python默认字符串编码

Python 何时、何地以及如何将编码隐式应用于字符串或进行隐式转码(转换)?

那些“默认”(即隐含)编码是什么?

例如,什么是编码:

python character-encoding python-2.x python-3.x python-unicode

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

如何在Python 3.6中解决UnicodeDecodeError?

我从Python 2.7切换到Python 3.6。

我有处理某些非英语内容的脚本。

我通常通过Cron和Terminal运行脚本。

我的python 2.7脚本中出现了UnicodeDecodeError,我解决了这个问题。

# encoding=utf8  
import sys  

reload(sys)  
sys.setdefaultencoding('utf8')
Run Code Online (Sandbox Code Playgroud)

现在在Python 3.6中,它不起作用。我有类似的打印语句print("Here %s" % (myvar)),它会引发错误。我可以通过将其替换为来解决此问题,myvar.encode("utf-8")但我不想用每个print语句编写。

PYTHONIOENCODING=utf-8在终端机上做了,但仍然有这个问题。

有没有更清洁的方法来解决UnicodeDecodeErrorPython 3.6中的问题?

有没有办法告诉Python3在utf-8中打印所有内容?就像我在Python2中所做的一样?

python unicode python-3.x

4
推荐指数
2
解决办法
9315
查看次数

如何将 .write() 用于外语字符(ã、à、ê、ó、...)

我正在 Python 3 中处理一个小项目,我必须扫描一个装满文件的驱动器并输出一个 .txt 文件,其中包含驱动器内所有文件的路径。问题是一些文件是巴西葡萄牙语,其中包含“重音字母”,例如“não”、“você”等,而这些特殊字母在最终的 .txt 中被错误地输出。

代码只是下面这几行:

import glob

path = r'path/path'

files = [f for f in glob.glob(path + "**/**", recursive=True)]

with open("file.txt", 'w') as output:
    for row in files:
        output.write(str(row.encode('utf-8') )+ '\n')
Run Code Online (Sandbox Code Playgroud)

输出示例

path\folder1\Treino_2.doc
path\folder1\Treino_1.doc
path\folder1\\xc3\x81gua de Produ\xc3\xa7\xc3\xa3o.doc
Run Code Online (Sandbox Code Playgroud)

最后一行显示了一些输出是如何错误的,因为x81gua de Produ\xc3\xa7\xc3\xa3o应该是Régua de Produção

python encoding glob python-3.x

2
推荐指数
1
解决办法
67
查看次数

重新加载模块会提供导入时最初无法使用的功能.我在哪里可以了解更多相关信息?

这段代码解决了我遇到的问题.但是,没有重新加载就无法使用"setdefaultencoding".

什么是这种语言的怪癖叫什么?为什么我之前没有告诉过?我在哪里可以阅读更多相关信息.

import sys;
reload(sys);
sys.setdefaultencoding("utf8")
Run Code Online (Sandbox Code Playgroud)

http://mypy.pythonblogs.com/12_mypy/archive/1253_workaround_for_python_bug_ascii_codec_cant_encode_character_uxa0_in_position_111_ordinal_not_in_range128.html

python

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

无法获取django模板标签返回unicode

我正在编写一个应用程序来跟踪2个玩家之间的一系列匹配.我正在使用Django的User模型并使用我自己的模型进行扩展UserProfile.

我将用户名存储User为steamID(例如:)76561197965801299,然后在登录时查找他们的用户名,并进行更新UserProfile.

而不是看着 76561197965801299,我想看一个用户名,在一个页面上,我想用更多好东西装饰这个用户名,所以我写了一个模板标签.

问题:

我似乎无法从我的模板标签打印unicode数据.

实际错误:

'ascii'编解码器无法对位置16中的字符u'\ u260e'进行编码:序数不在范围内(128)

通常Django不会打扰我的unicode问题(例如:我可以在管理页面中看到这个unicode对象没问题)但我从未尝试过应用模板标签,所以显然我在这里做错了.

模板/阶梯/ match_game_listing.html

{{ match.challengee|steam_name }}
Run Code Online (Sandbox Code Playgroud)

match.challengee这种情况下是76561197971597000.

梯/ templatetags/ladder_filters.py

from django import template
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist
from django.utils.html import mark_safe
from cafe.models import UserProfile

register = template.Library()

@register.filter()
def steam_name(name):
    try:
        user_obj = User.objects.get(username=name)
        user_prof = UserProfile.objects.get(user_id=user_obj.id)

        url = user_prof.url
        handle = unicode(user_prof.handle)
        avatar = user_prof.avatar

        steam_string = "<a …
Run Code Online (Sandbox Code Playgroud)

python django unicode django-templates

0
推荐指数
1
解决办法
3192
查看次数