2013-08-18 143 views
0

這涉及到以下幾個問題 -的UnicodeDecodeError: 'ASCII' 編解碼器不能解碼字節 - Python的

我有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.添加他們到不同的變量如下

名詞=「CAR」| 「BUS」|

verbs =「DRIVES」| 「命中」

5.現在我想將它們傳遞到NLTK背景如下自由語法 -

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

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

它給了我下面的錯誤 -

line 40, in 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

+0

你可以顯示錯誤的* full * traceback嗎? – Bakuriu

+0

我正在使用Pycharm。我如何打印完整的追溯? print_stack()不起作用。無論如何,可以找出與給定的例外問題? – ChamingaD

+0

'輸入日誌;嘗試:你的代碼;除了:logging.exception(「ouch」)'#爲了清楚起見,使用換行符和縮進代替';' –

回答

1

總之你有這些策略:

  • 對待輸入作爲字節序列,然後輸入和語法是UTF-8編碼的數據(字節)
  • 治療輸入爲unicode代碼點序列,則輸入和語法都是unicode。
  • 將unicode代碼點重命名爲ascii,即使用轉義序列。

與pip,2.0一起安裝的nltk。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文本,而不是普通的文本"€" VS bar

+0

嗯。如何將以上編碼應用於我的代碼? grammar = 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 V N - >'''+名詞+代詞+''' D - >'''+確定符+''' ADJ - >'''+形容詞+''' ADV - >'''+副詞+''' P - >'''+介詞+''' V - >'''+動詞+''' ''') – ChamingaD

相關問題