2013-10-15 9 views
6

段落を単語に分割しようとしています。 lovely nltk.tokenize.word_tokenize(送信済み)が手元にありますが、help(word_tokenize)は「このトークナイザは一度に文章を処理するように設計されています」と述べています。nltkの悪用の結果word_tokenize(送信済み)

段落に最大5文を使用すると、何が起こるかを知りませんか?私はいくつかの短いパラグラフでそれを試してみましたが、うまくいくように見えますが、それは決して決定的な証拠ではありません。

+1

'nltk.word_tokenize()'今のテキストに取り組んでいます複数の文を含む。 – nedned

答えて

7

nltk.tokenize.word_tokenize(text)は、単に明らかに文章を解析する単純な正規表現を使用しTreebankWordTokenizerクラスのインスタンスのtokenizeメソッドを呼び出し薄いwrapper functionあります。このトークナイザは、テキストはすでに 文に分割されていることを前提と

そのクラスのドキュメントには、と述べています。文字列の末尾にあるピリオドとは別のピリオド( など)は、添付されている単語の一部(たとえば、 略語など)とみなされ、個別にトークン化されません。

基礎となるtokenize方法自体は非常に簡単です:

def tokenize(self, text): 
    for regexp in self.CONTRACTIONS2: 
     text = regexp.sub(r'\1 \2', text) 
    for regexp in self.CONTRACTIONS3: 
     text = regexp.sub(r'\1 \2 \3', text) 

    # Separate most punctuation 
    text = re.sub(r"([^\w\.\'\-\/,&])", r' \1 ', text) 

    # Separate commas if they're followed by space. 
    # (E.g., don't separate 2,500) 
    text = re.sub(r"(,\s)", r' \1', text) 

    # Separate single quotes if they're followed by a space. 
    text = re.sub(r"('\s)", r' \1', text) 

    # Separate periods that come before newline or end of string. 
    text = re.sub('\. *(\n|$)', ' . ', text) 

    return text.split() 

は基本的に、どのような方法が通常行うことは、それは文字列の末尾に該当する場合、別のトークンとして期間をトークン化である:

>>> nltk.tokenize.word_tokenize("Hello, world.") 
['Hello', ',', 'world', '.'] 

文字列の中にある任意のピリオドは、略語を前提として、単語の一部としてトークン化されます。

>>> nltk.tokenize.word_tokenize("Hello, world. How are you?") 
['Hello', ',', 'world.', 'How', 'are', 'you', '?'] 

その動作が許容される限り、正常であるはずです。

+0

ああ、その動作は受け入れられません、私はテキストの分類を行うために単語の頻度を使用しています。どのような徹底的な答え、ありがとう! –

+1

このアドバイスは時代遅れです。 'nltk.word_tokenize()'はトークンを決定する前にPunk sentence tokenizerを使って文を分割するようになりました。 – nedned

1

ハックのこの種を試してみてください:

>>> from string import punctuation as punct 
>>> sent = "Mr President, Mr President-in-Office, indeed we know that the MED-TV channel and the newspaper Özgür Politika provide very in-depth information. And we know the subject matter. Does the Council in fact plan also to use these channels to provide information to the Kurds who live in our countries? My second question is this: what means are currently being applied to integrate the Kurds in Europe?" 
# Add spaces before punctuations 
>>> for ch in sent: 
...  if ch in punct: 
...    sent = sent.replace(ch, " "+ch+" ") 
# Remove double spaces if it happens after adding spaces before punctuations. 
>>> sent = " ".join(sent.split()) 

はその後、おそらく次のコードは、あなたがあまりにも周波数をカウントするために必要なものである=)

>>> from nltk.tokenize import word_tokenize 
>>> from nltk.probability import FreqDist 
>>> fdist = FreqDist(word.lower() for word in word_tokenize(sent)) 
>>> for i in fdist: 
...  print i, fdist[i] 
+0

偉大なハック!私はそれをショットを与えるよ! –

関連する問題