【发布时间】:2013-08-20 04:27:25
【问题描述】:
这与以下问题有关-
- Python unicode equal comparison failed
- Find word infront and behind of a Python list
- Searching for Unicode characters in Python
- NLTK Context Free Grammar Genaration
我有 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 Python 和 Find 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 ?
【问题讨论】:
-
你能显示错误的完整回溯吗?
-
我正在使用 Pycharm。如何打印完整的回溯? print_stack() 不起作用。无论如何都可以找出给定异常的问题?
-
import logging; try: your-code; except: logging.exception("ouch")# 为清楚起见,使用换行符和缩进代替; -
请同时粘贴定义
nouns和verbs的正确代码。看,"CAR" | "BUS"(字面意思)在 Python 中是不可能的,我猜这是传递给解析器的一些字符串? -
@qarma 我将附上完整的代码供您参考。名词和动词是变量,它以“CAR”格式保存一些 unicode 文本 | “巴士”