2012-02-23 7 views
0

タグ付き段落からすべての固有名詞を抽出しようとしています。私がコードで行ったことは、最初に段落を別々に抽出し、その中に固有名詞があるかどうかを確認したことです。しかし、問題は、私は適切な名詞を抽出することができていないということです。私のコードは特定のタグをチェックするループの中に入ることさえありません。Pythonを使用するチャンク

私のコード: 'tesu.txt' 私は、段落からすべてのタグ付けされた固有名詞を抽出することができますどのように

Several/ap defendants/nns in/in the/at Summerdale/np police/nn burglary/nn trial/nn  made/vbd statements/nns indicating/vbg their/pp$ guilt/nn at/in the/at.... 

Bellows/np made/vbd the/at disclosure/nn when/wrb he/pps asked/vbd Judge/nn-tl Parsons/np to/to grant/vb his/pp$ client/nn ,/, Alan/np Clements/np ,/, 30/cd ,/, a/at separate/jj trial/nn ./. 

から

def noun(sen): 
m=[] 
if (sen.split('/')[1].lower().startswith('np')&sen.split('/')[1].lower().endswith('np')): 
     w=sen.strip().split('/')[0] 
     m.append(w) 
return m 


import nltk 
rp = open("tesu.txt", 'r') 
text = rp.read() 
list = [] 
sentences = splitParagraph(text) 
for s in sentences: 
list.append(s) 

サンプル入力?

+0

タグ付き段落の例を示してください。そうでなければ、コードが適切なことをしているかどうかを判断できません。 – DNA

+0

@DNA私はサンプル入力を受けています。確認はありがたいです – user1052462

答えて

1

ありがとう、データサンプルです。

あなたがする必要がある:

  • は、例えば、各タグ付けされた単語を抽出するために、空白文字で行を分割し、各段落/ラインを読んでSummerdale/np
  • が(だから、もしそうならそれはnp
  • をタグ付けされているかどうかを確認するために/によって次のようなものを自分の名詞リストに分割(実際の単語)の他の半分を追加

を単語に分割しました!ボグダンの回答に基づいて、感謝)

あなたの例のデータのために、生成
def noun(word): 
    nouns = [] 
    for word in sentence.split(): 
     word, tag = word.split('/') 
     if (tag.lower() == 'np'): 
     nouns.append(word); 
    return nouns 

if __name__ == '__main__': 
    nouns = [] 
    with open('tesu.txt', 'r') as file_p: 
     for sentence in file_p.read().split('\n\n'): 
       result = noun(sentence) 
       if result: 
        nouns.extend(result) 
    print nouns 

['Summerdale', 'Bellows', 'Parsons', 'Alan', 'Clements'] 

更新:あなたは名詞から来た段落気にしない場合

nouns = [] 
with open('tesu.txt', 'r') as file_p: 
    for word in file_p.read().split(): 
    word, tag = word.split('/') 
    if (tag.lower() == 'np'): 
     nouns.append(word) 
print nouns 

:実際には、あなたがダウンし、これに全体を短縮することができます。

タグが例のように常に小文字である場合は、.lower()も取り除くことができます。

0

コードスタイルで作業する必要があります。そこには不必要なループがたくさんあると思います。あなたはsplitParagraphにも、既存のsplitメソッドだけを呼び出す不要なメソッドがありますが、その後は使用しないでください。import reまた、あなたのコードを識別すると、このようにするのは非常に難しいです。入力のサンプルを"tesu.txt"から提供する必要があります。とにかくあなたのコードはすべてコンパクトにできます:

def noun(sentence); 
    word, tag = sentence.split('/') 
    if (tag.lower().startswith('np') and tag.lower().endswith('np')): 
     return word 
    return False 

if __name__ == '__main__' 
    words = [] 
    with open('tesu.txt', 'r') as file_p: 
     for sentence in file_p.read().split('\n\n'): 
       result = noun(sentence) 
       if result: 
        words.append(result) 
+0

ありがとうございます。しかし、あなたのコードで試してみると、エラーが返されます。 word、tag = sentence.split( '/') ValueError:アンパックする値が多すぎます。上記のサンプル入力があります – user1052462

関連する問題