2012-03-08 72 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','.'],这就是导致你的错误的原因。