【问题标题】:UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 13: ordinal not in range(128)UnicodeDecodeError:“ascii”编解码器无法解码位置 13 中的字节 0xe2:序数不在范围内(128)
【发布时间】:2013-09-10 01:35:19
【问题描述】:

我正在使用 NLTK 对我的文本文件执行 kmeans 聚类,其中每一行都被视为一个文档。例如,我的文本文件是这样的:

belong finger death punch <br>
hasty <br>
mike hasty walls jericho <br>
jägermeister rules <br>
rules bands follow performing jägermeister stage <br>
approach 

现在我要运行的演示代码是这样的:

import sys

import numpy
from nltk.cluster import KMeansClusterer, GAAClusterer, euclidean_distance
import nltk.corpus
from nltk import decorators
import nltk.stem

stemmer_func = nltk.stem.EnglishStemmer().stem
stopwords = set(nltk.corpus.stopwords.words('english'))

@decorators.memoize
def normalize_word(word):
    return stemmer_func(word.lower())

def get_words(titles):
    words = set()
    for title in job_titles:
        for word in title.split():
            words.add(normalize_word(word))
    return list(words)

@decorators.memoize
def vectorspaced(title):
    title_components = [normalize_word(word) for word in title.split()]
    return numpy.array([
        word in title_components and not word in stopwords
        for word in words], numpy.short)

if __name__ == '__main__':

    filename = 'example.txt'
    if len(sys.argv) == 2:
        filename = sys.argv[1]

    with open(filename) as title_file:

        job_titles = [line.strip() for line in title_file.readlines()]

        words = get_words(job_titles)

        # cluster = KMeansClusterer(5, euclidean_distance)
        cluster = GAAClusterer(5)
        cluster.cluster([vectorspaced(title) for title in job_titles if title])

        # NOTE: This is inefficient, cluster.classify should really just be
        # called when you are classifying previously unseen examples!
        classified_examples = [
                cluster.classify(vectorspaced(title)) for title in job_titles
            ]

        for cluster_id, title in sorted(zip(classified_examples, job_titles)):
            print cluster_id, title

(也可以找到here

我收到的错误是这样的:

Traceback (most recent call last):
File "cluster_example.py", line 40, in
words = get_words(job_titles)
File "cluster_example.py", line 20, in get_words
words.add(normalize_word(word))
File "", line 1, in
File "/usr/local/lib/python2.7/dist-packages/nltk/decorators.py", line 183, in memoize
result = func(*args)
File "cluster_example.py", line 14, in normalize_word
return stemmer_func(word.lower())
File "/usr/local/lib/python2.7/dist-packages/nltk/stem/snowball.py", line 694, in stem
word = (word.replace(u"\u2019", u"\x27")
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 13: ordinal not in range(128)

这里发生了什么?

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:

    文件被读取为一堆strs,但它应该是unicodes。 Python 尝试隐式转换,但失败了。变化:

    job_titles = [line.strip() for line in title_file.readlines()]
    

    strs 显式解码为unicode(此处假设为UTF-8):

    job_titles = [line.decode('utf-8').strip() for line in title_file.readlines()]
    

    也可以通过导入the codecs module并使用codecs.open而不是内置的open来解决。

    【讨论】:

    • 运行此 line.decode('utf-8').strip().lower().split() 也会给我同样的错误。我添加了 .deocode('utf-8')
    • @kathirraja:你能提供一个参考吗?据我所知,即使在 Python 3 中,decode 方法仍然是将字节字符串解码为 Unicode 字符串的首选方法。 (虽然,我的答案中的类型不适用于 Python 3 - 对于 Python 3,我们正在尝试从 bytes 转换为 str,而不是从 str 转换为 unicode。)
    【解决方案2】:

    这对我来说很好。

    f = open(file_path, 'r+', encoding="utf-8")
    

    可以添加第三个参数encoding,保证编码类型为'utf-8'

    注意:此方法在 Python3 中运行良好,我在 Python2.7 中没有尝试过。

    【讨论】:

    • 它在 Python 2.7.10 中不起作用:TypeError: 'encoding' is an invalid keyword argument for this function
    • 它在 Python 2.7.10 中不起作用:TypeError: 'encoding' is an invalid keyword argument for this function 这很好用:import io with io.open(file_path, 'r', encoding="utf-8") as f: for line in f: do_something(line)
    • 在 python3.6 中的工作就像一个魅力非常感谢!
    【解决方案3】:

    对我来说,终端编码有问题。将 UTF-8 添加到 .bashrc 解决了这个问题:

    export LC_CTYPE=en_US.UTF-8
    

    之后别忘了重新加载 .bashrc:

    source ~/.bashrc
    

    【讨论】:

    • 我不得不在 Ubuntu 18.04.3 和 Python 3.6.8 上使用 export LC_ALL=C.UTF-8。否则这解决了我的问题,谢谢。
    • 对我来说,在 macOS 10.15.7 和 Python 3.6.7 上使用 set -x LANG en_US.UTF-8 (fish) 解决了这个问题
    【解决方案4】:

    你也可以试试这个:

    import sys
    reload(sys)
    sys.setdefaultencoding('utf8')
    

    【讨论】:

    • 这意味着什么?听起来它是全球性的,不仅适用于这个文件。
    • 请注意,上述内容在 Python 3 中已弃用。
    【解决方案5】:

    尝试在 Docker 容器中安装 python 包时出现此错误。对我来说,问题是 docker 映像没有配置 locale。将以下代码添加到 Dockerfile 为我解决了这个问题。

    # Avoid ascii errors when reading files in Python
    RUN apt-get install -y locales && locale-gen en_US.UTF-8
    ENV LANG='en_US.UTF-8' LANGUAGE='en_US:en' LC_ALL='en_US.UTF-8'
    

    【讨论】:

    【解决方案6】:

    在 Ubuntu 18.04 上使用 Python3.6 我已经解决了这两个问题:

    with open(filename, encoding="utf-8") as lines:
    

    如果您将工具作为命令行运行:

    export LC_ALL=C.UTF-8
    

    请注意,如果您使用的是 Python2.7,则必须以不同方式处理此问题。首先你必须设置默认编码:

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

    然后要加载文件,您必须使用io.open 设置编码:

    import io
    with io.open(filename, 'r', encoding='utf-8') as lines:
    

    你仍然需要导出环境

    export LC_ALL=C.UTF-8
    

    【讨论】:

      【解决方案7】:

      要查找任何和所有 unicode 错误相关...使用以下命令:

      grep -r -P '[^\x00-\x7f]' /etc/apache2 /etc/letsencrypt /etc/nginx
      

      找到我的

      /etc/letsencrypt/options-ssl-nginx.conf:        # The following CSP directives don't use default-src as 
      

      使用shed,我发现了有问题的序列。原来是编辑失误。

      00008099:     C2  194 302 11000010
      00008100:     A0  160 240 10100000
      00008101:  d  64  100 144 01100100
      00008102:  e  65  101 145 01100101
      00008103:  f  66  102 146 01100110
      00008104:  a  61  097 141 01100001
      00008105:  u  75  117 165 01110101
      00008106:  l  6C  108 154 01101100
      00008107:  t  74  116 164 01110100
      00008108:  -  2D  045 055 00101101
      00008109:  s  73  115 163 01110011
      00008110:  r  72  114 162 01110010
      00008111:  c  63  099 143 01100011
      00008112:     C2  194 302 11000010
      00008113:     A0  160 240 10100000
      

      【讨论】:

        【解决方案8】:

        使用open(fn, 'rb').read().decode('utf-8') 而不仅仅是open(fn).read()

        【讨论】:

          【解决方案9】:

          你可以在使用job_titles字符串之前试试这个:

          source = unicode(job_titles, 'utf-8')
          

          【讨论】:

          • 对于 Python2 还是 Python3 也是如此?
          【解决方案10】:

          对于 python 3,默认编码为“utf-8”。基本文档中建议以下步骤:https://docs.python.org/2/library/csv.html#csv-examples 以防出现任何问题

          1. 创建一个函数

            def utf_8_encoder(unicode_csv_data):
                for line in unicode_csv_data:
                    yield line.encode('utf-8')
            
          2. 然后使用阅读器内部的函数,例如

            csv_reader = csv.reader(utf_8_encoder(unicode_csv_data))
            

          【讨论】:

            【解决方案11】:

            python3x 或更高版本

            1. 在字节流中加载文件:
                 body = ''
                    for lines in open('website/index.html','rb'):
                        decodedLine = lines.decode('utf-8')
                        body = body+decodedLine.strip()
                    return body
            
            1. 使用全局设置:
                import io
                import sys
                sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8')
            

            【讨论】:

              猜你喜欢
              • 2017-09-19
              • 1970-01-01
              • 1970-01-01
              • 2012-06-11
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多