2011-02-09 11 views
62

私のタイトルに対する答えは、文書を読むことですが、NLTK bookを実行しましたが、答えが得られません。私はPythonにはまったく新しいものです。NLTKで新しいコーパスを作成する

私は.txt個のファイルを持っており、NLTKがコーパスnltk_data用に提供するコーパス機能を使用したいと考えています。

私はPlaintextCorpusReaderを試みたが、私はさらによりも得ることができませんでした:

>>>import nltk 
>>>from nltk.corpus import PlaintextCorpusReader 
>>>corpus_root = './' 
>>>newcorpus = PlaintextCorpusReader(corpus_root, '.*') 
>>>newcorpus.words() 

PUNKTを使用してnewcorpus文章はIセグメントをどうすればよいですか?私はpunkt関数を使用しようとしましたが、punkt関数はPlaintextCorpusReaderクラスを読み取れませんでしたか?

また、セグメント化されたデータをテキストファイルに書き込む方法に私を導くことができますか?

編集: この質問には一度賞金がありましたが、今すぐに2番目の賞金があります。バウンティボックスのテキストを参照してください。

答えて

32

少なくとも入力言語が英語の場合、PlaintextCorpusReaderはすでに入力をpunktトークナイザで分割していると思います。

PlainTextCorpusReader's constructor

def __init__(self, root, fileids, 
      word_tokenizer=WordPunctTokenizer(), 
      sent_tokenizer=nltk.data.LazyLoader(
       'tokenizers/punkt/english.pickle'), 
      para_block_reader=read_blankline_block, 
      encoding='utf8'): 

あなたは読者に単語や文章トークナイザを渡すことができますが、後者のデフォルトはすでに​​です。

単一文字列の場合、トークナイザは次のように使用されます(here、punktトークナイザのセクション5を参照)。

>>> import nltk.data 
>>> text = """ 
... Punkt knows that the periods in Mr. Smith and Johann S. Bach 
... do not mark sentence boundaries. And sometimes sentences 
... can start with non-capitalized words. i is a good variable 
... name. 
... """ 
>>> tokenizer = nltk.data.load('tokenizers/punkt/english.pickle') 
>>> tokenizer.tokenize(text.strip()) 
+0

ありがとう。とった。分割された文章を分割されたtxtファイルに出力するにはどうすればよいですか? – alvas

+0

両方のリンクにエラーがあります、404.いくつかの甘い魂がリンクを更新できますか? – mtk

+0

最初のリンクを修正しました。どの文書が第2のものを指していたかは分かりません。 – alexis

9
>>> import nltk 
>>> from nltk.corpus import PlaintextCorpusReader 
>>> corpus_root = './' 
>>> newcorpus = PlaintextCorpusReader(corpus_root, '.*') 
""" 
if the ./ dir contains the file my_corpus.txt, then you 
can view say all the words it by doing this 
""" 
>>> newcorpus.words('my_corpus.txt') 
+0

devnagari言語の問題を起こします。 – ashim888

44

それがどのように動作するかを考え出すのいくつかの年後、ここではテキストファイルのディレクトリとNLTKコーパスを作成する方法

の更新チュートリアルですか?

主な考え方は、nltk.corpus.readerパッケージを使用することです。 にテキストファイルのディレクトリがある場合は、PlaintextCorpusReaderを使用することをお勧めします。

あなたはこのようになりますディレクトリがある場合:

newcorpus/ 
     file1.txt 
     file2.txt 
     ... 

単純にコード行を使用して、コーパス得ることができます。

import os 
from nltk.corpus.reader.plaintext import PlaintextCorpusReader 

corpusdir = 'newcorpus/' # Directory of corpus. 

newcorpus = PlaintextCorpusReader(corpusdir, '.*') 

は注:PlaintextCorpusReaderが使用するをデフォルトのnltk.tokenize.sent_tokenize()nltk.tokenize.word_tokenize()は、テキストを文章と単語に分割し、これらの機能は英語のために構築されています。はすべてのために機能します言語。

最後に
import os 
from nltk.corpus.reader.plaintext import PlaintextCorpusReader 

# Let's create a corpus with 2 texts in different textfile. 
txt1 = """This is a foo bar sentence.\nAnd this is the first txtfile in the corpus.""" 
txt2 = """Are you a foo bar? Yes I am. Possibly, everyone is.\n""" 
corpus = [txt1,txt2] 

# Make new dir for the corpus. 
corpusdir = 'newcorpus/' 
if not os.path.isdir(corpusdir): 
    os.mkdir(corpusdir) 

# Output the files into the directory. 
filename = 0 
for text in corpus: 
    filename+=1 
    with open(corpusdir+str(filename)+'.txt','w') as fout: 
     print>>fout, text 

# Check that our corpus do exist and the files are correct. 
assert os.path.isdir(corpusdir) 
for infile, text in zip(sorted(os.listdir(corpusdir)),corpus): 
    assert open(corpusdir+infile,'r').read().strip() == text.strip() 


# Create a new corpus by specifying the parameters 
# (1) directory of the new corpus 
# (2) the fileids of the corpus 
# NOTE: in this case the fileids are simply the filenames. 
newcorpus = PlaintextCorpusReader('newcorpus/', '.*') 

# Access each file in the corpus. 
for infile in sorted(newcorpus.fileids()): 
    print infile # The fileids of each file. 
    with newcorpus.open(infile) as fin: # Opens the file. 
     print fin.read().strip() # Prints the content of the file 
print 

# Access the plaintext; outputs pure string/basestring. 
print newcorpus.raw().strip() 
print 

# Access paragraphs in the corpus. (list of list of list of strings) 
# NOTE: NLTK automatically calls nltk.tokenize.sent_tokenize and 
#  nltk.tokenize.word_tokenize. 
# 
# Each element in the outermost list is a paragraph, and 
# Each paragraph contains sentence(s), and 
# Each sentence contains token(s) 
print newcorpus.paras() 
print 

# To access pargraphs of a specific fileid. 
print newcorpus.paras(newcorpus.fileids()[0]) 

# Access sentences in the corpus. (list of list of strings) 
# NOTE: That the texts are flattened into sentences that contains tokens. 
print newcorpus.sents() 
print 

# To access sentences of a specific fileid. 
print newcorpus.sents(newcorpus.fileids()[0]) 

# Access just tokens/words in the corpus. (list of strings) 
print newcorpus.words() 

# To access tokens of a specific fileid. 
print newcorpus.words(newcorpus.fileids()[0]) 

、テキストのディレクトリを読み、NLTKを作成するには:

ここではどのように異なるレベルでコーパスにアクセスするために、テスト用テキストファイルの作成方法と、NLTKでコーパスを作成し、との完全なコードです

>>> from nltk.tokenize import sent_tokenize, word_tokenize 
>>> txt1 = """This is a foo bar sentence.\nAnd this is the first txtfile in the corpus.""" 
>>> sent_tokenize(txt1) 
['This is a foo bar sentence.', 'And this is the first txtfile in the corpus.'] 
>>> word_tokenize(sent_tokenize(txt1)[0]) 
['This', 'is', 'a', 'foo', 'bar', 'sentence', '.'] 
:別の言語のコーパスには、最初にあなたのpython-呼び出し可能 単語トークン化文のトークン化文字列/ basestring入力を受け取り、このような出力を生成モジュールを持っていることを確認する必要があります説明のために
+0

ご清聴ありがとうございます。ただし、多くの言語がデフォルトでサポートされています。 –

+0

誰かが 'AttributeError:__exit__'エラーを受け取った場合。 'with()'の代わりに 'open()'を使用してください –

+0

@TasdikRahmanあなたは詳細を教えてください。私はこれを通過することはできません.. – yashhy

関連する問題