86

多くの場合、自分のタイトルに対する答えはドキュメンテーションを読んで読むことだと思いましたが、NLTK の本を一通り読みましたが、答えが得られませんでした。私はPythonが初めてです。

多数の.txtファイルがあり、NLTK がコーパスに提供するコーパス関数を使用できるようにしたいと考えていますnltk_data

私は試しましPlaintextCorpusReaderたが、それ以上のことはできませんでした:

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

newcorpuspunkt を使用して文を分割するにはどうすればよいですか? PlaintextCorpusReaderpunkt 関数を使用してみましたが、punkt 関数はクラスを読み取れませんでしたか?

また、セグメント化されたデータをテキスト ファイルに書き込む方法を教えてもらえますか?

4

4 に答える 4

71

それがどのように機能するかを数年間理解した後、更新されたチュートリアルがここにあります

テキストファイルのディレクトリで NLTK コーパスを作成するには?

主なアイデアは、nltk.corpus.readerパッケージを利用することです。Englishのテキストファイルのディレクトリがある場合は、 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()テキストを文と単語に分割します。これらの関数は英語用に作成されているため、すべての言語で機能するとは限りません。

テストテキストファイルの作成を含む完全なコードと、NLTK を使用してコーパスを作成する方法、およびさまざまなレベルでコーパスにアクセスする方法を次に示します。

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 コーパスを作成するには、最初に、文字列/ベース文字列の入力を受け取り、そのような出力を生成する、python 呼び出し可能な単語のトークン化および文のトークン化モジュールがあることを確認する必要があります。

>>> 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', '.']
于 2014-01-04T14:29:11.020 に答える
41

PlaintextCorpusReader少なくとも入力言語が英語の場合は、既にパンクトトークナイザーで入力をセグメント化していると思います。

PlainTextCorpusReader のコンストラクタ

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'):

リーダーに単語と文のトークナイザーを渡すことができますが、後者の場合、デフォルトは既に ですnltk.data.LazyLoader('tokenizers/punkt/english.pickle')

単一の文字列の場合、トークナイザーは次のように使用されます (ここで説明されています。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())
于 2011-02-10T00:42:42.030 に答える
14
 >>> 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')
于 2011-02-25T04:11:22.787 に答える
1
from nltk.corpus.reader.plaintext import PlaintextCorpusReader


filecontent1 = "This is a cow"
filecontent2 = "This is a Dog"

corpusdir = 'nltk_data/'
with open(corpusdir + 'content1.txt', 'w') as text_file:
    text_file.write(filecontent1)
with open(corpusdir + 'content2.txt', 'w') as text_file:
    text_file.write(filecontent2)

text_corpus = PlaintextCorpusReader(corpusdir, ["content1.txt", "content2.txt"])

no_of_words_corpus1 = len(text_corpus.words("content1.txt"))
print(no_of_words_corpus1)
no_of_unique_words_corpus1 = len(set(text_corpus.words("content1.txt")))

no_of_words_corpus2 = len(text_corpus.words("content2.txt"))
no_of_unique_words_corpus2 = len(set(text_corpus.words("content2.txt")))

enter code here
于 2020-10-10T23:10:12.280 に答える