2012-03-08 74 views
0

我試圖從標記文件中提取專有名詞。但問題是,我是用有時試圖代碼給出了一個錯誤,即:python錯誤 - 太多值

Traceback (most recent call last): 
File "E:\pt\paragraph", line 35, in <module> 
sen1= noun(mylist[s]) 
File "E:\pt\paragraph", line 5, in noun 
word, tag = word.split('/') 
ValueError: too many values to unpack 

的代碼工作正常,一些文本但對於一些它給人的錯誤。

代碼:

def noun(words): 
nouns = [] 
for word in words.split(): 
word, tag = word.split('/') 
    if (tag.lower() == 'np'): 
    nouns.append(word); 
return nouns 

def splitParagraph(paragraph): 

import re 
paragraphs = paragraph.split('\n\n') 
return paragraphs 

if __name__ == '__main__': 
import nltk 
rp = open("t3.txt", 'r') 
text = rp.read() 
mylist = [] 
para = splitParagraph(text) 

for s in para: 
mylist.append(s) 
for s in range(len(mylist)-1): 
sen1= noun(mylist[s]) 
sen2= noun(mylist[s+1]) 

當前我與作品想如果我刪除的第一段其他明智它給人的錯誤。

樣的文字:

A/at good/jj man/nn-hl departs/vbz-hl ./. Goodbye/uh-hl ,/,-hl Mr./np-hl Sam/np-hl./. Sam/np Rayburn/np was/bedz a/at good/jj man/nn ,/, a/at good/jj American/np ,/, and/cc ,/, third/od ,/, a/at good/jj Democrat/np ./. He/pps was/bedz all/abn of/in these/dts rolled/vbn into/in one/cd sturdy/jj figure/nn ;/. ;/. Mr./np Speaker/nn-tl ,/, Mr./np Sam/np ,/, and/cc Mr./np Democrat/np ,/, at/in one/cd and/cc the/at same/ap time/nn ./. 

The/at House/nn-tl was/bedz his/pp$ habitat/nn and/cc there/rb he/pps flourished/vbd ,/, first/rb as/cs a/at young/jj representative/nn ,/, then/rb as/cs a/at forceful/jj committee/nn chairman/nn ,/, and/cc finally/rb in/in the/at post/nn for/in which/wdt he/pps seemed/vbd intended/vbn from/in birth/nn ,/, Speaker/nn-tl of/in-tl the/at-tl House/nn-tl ,/, and/cc second/od most/ql powerful/jj man/nn in/in Washington/np ./. 

如果我刪除了第1段(A /在好/ JJ人/ NN-HL離開......)代碼工作。如何解決這個問題呢。

在此先感謝。

回答

1

你的「單詞」包含多個「/」。 所以開箱它變成(標籤,單詞)將無法正常工作。你必須弄清楚你想如何處理你的標籤/單詞有多個「/」的情況。

def noun(words): 
    nouns = [] 
    for word in words.split(): 
     items = word.split('/') 
     if len(items) == 2: 
      tag, word = items 
     else: 
      # do something else to parse 

    .... 

我才意識到,你可以使用「maxsplit」選項來分離方法的字符串,如果你只是想拆就在第一「/」。

>>> word = "a/b/c" 
>>> 
>>> word.split("/", 1) 
['a', 'b/c'] 
0

您在'/'處分割並嘗試獲得2個值。但是,你必須擁有一個「字」不止一個「/」 !:

Sam/np-hl./. 

所以,你得到[「薩姆」,「NP-HL」,「」]你試圖給只兩個變量。

0

該錯誤表示split()方法的返回數超過了「解包」到=符號左側的變量數。

下面是一個例子:

>>> x,y = 'a,b,c,d'.split(',') 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
ValueError: too many values to unpack 
>>> x,y,z,t = 'a,b,c,d'.split(',') 

因此,這意味着什麼,你是word包含超過2對tags

問題是這個「對」:Sam/np-hl./.它沒有空間,所以當你拆分這對時,你實際上得到了['Sam','np-hl','.'],這就是導致你的錯誤的原因。