【问题标题】:UnicodeDecodeError: 'ascii' codec can't decode byte - PythonUnicodeDecodeError:“ascii”编解码器无法解码字节 - Python
【发布时间】:2013-08-20 04:27:25
【问题描述】:

这与以下问题有关-

我有 python 应用程序执行以下任务 -

# -*- coding: utf-8 -*-

1.读取 unicode 文本文件(非英文)-

def readfile(file, access, encoding):
    with codecs.open(file, access, encoding) as f:
        return f.read()

text = readfile('teststory.txt','r','utf-8-sig')

这会将给定的文本文件作为字符串返回。

2。将文本拆分成句子。

3.浏览每个句子中的单词并识别动词、名词等。

参考 - Searching for Unicode characters in PythonFind word infront and behind of a Python list

4.将它们添加到单独的变量中,如下所示

名词 = "汽车" | “巴士”|

动词 = "驱动器" | “命中”

5.现在我正在尝试将它们传递给 NLTK 上下文无关语法,如下所示 -

grammar = nltk.parse_cfg('''
    S -> NP VP
    NP -> N
    VP -> V | NP V

    N -> '''+nouns+'''
    V -> '''+verbs+'''
    ''')

它给了我以下错误-

第 40 行,在 V -> '''+verbs+''' UnicodeDecodeError: 'ascii' codec can't decode byte 0xe0 in position 114: ordinal not in range(128)

我怎样才能克服这个问题并将变量传递给 NLTK CFG ?

完整代码 - https://dl.dropboxusercontent.com/u/4959382/new.zip

【问题讨论】:

  • 你能显示错误的完整回溯吗?
  • 我正在使用 Pycharm。如何打印完整的回溯? print_stack() 不起作用。无论如何都可以找出给定异常的问题?
  • import logging; try: your-code; except: logging.exception("ouch") # 为清楚起见,使用换行符和缩进代替;
  • 请同时粘贴定义nounsverbs 的正确代码。看,"CAR" | "BUS"(字面意思)在 Python 中是不可能的,我猜这是传递给解析器的一些字符串?
  • @qarma 我将附上完整的代码供您参考。名词和动词是变量,它以“CAR”格式保存一些 unicode 文本 | “巴士”

标签: python unicode nltk


【解决方案1】:

总体而言,您有以下策略:

  • 将输入视为字节序列,则输入和语法都是 utf-8 编码的数据(字节)
  • 将输入视为 unicode 代码点序列,然后输入和语法都是 unicode。
  • 将 unicode 代码点重命名为 ascii,即使用转义序列。

使用 pip 安装的 nltk,在我的情况下为 2.0.4,不直接接受 unicode,但接受引用的 unicode 常量,以下所有似乎都有效:

In [26]: nltk.parse_cfg(u'S -> "\N{EURO SIGN}" | bar')
Out[26]: <Grammar with 2 productions>

In [27]: nltk.parse_cfg(u'S -> "\N{EURO SIGN}" | bar'.encode("utf-8"))
Out[27]: <Grammar with 2 productions>

In [28]: nltk.parse_cfg(u'S -> "\N{EURO SIGN}" | bar'.encode("unicode_escape"))
Out[28]: <Grammar with 2 productions>

请注意,我引用了 unicode 文本而不是普通文本 "€"bar

【讨论】:

  • 嗯。如何将上述编码应用于我的代码?语法 = nltk.parse_cfg(''' S -> NP VP NP -> N | DN | ADJ N | ADJ NP | DNP | D ADJ NP | ADJ NNNNN DET VP -> V | NP V | ADV VN -> '' '+名词+代词+''' D -> '''+限定词+''' ADJ -> '''+形容词+''' ADV -> '''+副词+''' P -> '''+介词+' '' V -> '''+动词+''' ''')
猜你喜欢
  • 2014-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-09
  • 2018-08-02
  • 2013-09-23
  • 2013-06-17
  • 1970-01-01
相关资源
最近更新 更多