2011-02-09 18 views
62

Sądziłem, że często odpowiedzią na mój tytuł jest przeczytanie dokumentacji, ale przebiegłem przez NLTK book, ale to nie daje odpowiedzi. Jestem nowy dla Pythona.Tworzenie nowego korpusu z NLTK

Mam kilka plików .txt i chcę mieć możliwość korzystania z funkcji korpusu, które zapewnia NLTK dla korpusu nltk_data.

Próbowałem PlaintextCorpusReader ale nie mogłem się dalej niż:

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

jaki sposób segmentu I newcorpus zdań używając punkt? Próbowałem użyć funkcji punkt, ale funkcja punkt nie mogła odczytać klasy PlaintextCorpusReader?

Czy możesz również doprowadzić mnie do tego, w jaki sposób mogę zapisać posegmentowane dane w plikach tekstowych?

Edytuj: To pytanie miało kiedyś nagrodę, a teraz ma drugą nagrodę. Zobacz tekst w polu bounty.

Odpowiedz

32

Myślę, że PlaintextCorpusReader już segmentuje dane wejściowe z tokenizerem punktów, przynajmniej jeśli twój język wejściowy jest angielski.

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

można przekazać czytelnikowi słowo i zdanie tokenizer, ale ten ostatni jest już domyślnym nltk.data.LazyLoader('tokenizers/punkt/english.pickle').

W przypadku pojedynczego łańcucha użyty zostanie tokenizer w następujący sposób (wyjaśniony here, patrz punkt 5 dla tokenarza punktów).

>>> 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

dzięki za wyjaśnienie. Rozumiem. ale jak wypisać segmentowane zdania do oddzielnego pliku txt? – alvas

+0

Oba błędy są błędne, 404. Czy jakaś słodka dusza może zaktualizować linki? – mtk

+0

Naprawiono pierwsze łącze. Nie mam pojęcia, jaki dokument wskazywał drugi. – 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

Występuje problem z językiem devnagari. – ashim888

44

Po kilku latach na zastanawianie się, jak to działa, oto zaktualizowany poradnik z

Jak stworzyć korpus NLTK z katalogu TextFiles?

Głównym pomysłem jest skorzystanie z pakietu nltk.corpus.reader. W przypadku, gdy masz katalog plików tekstowych w English, najlepiej jest użyć PlaintextCorpusReader.

Jeśli masz katalog, który wygląda tak:

newcorpus/ 
     file1.txt 
     file2.txt 
     ... 

prostu użyć te linie kodu i można uzyskać corpus:

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

corpusdir = 'newcorpus/' # Directory of corpus. 

newcorpus = PlaintextCorpusReader(corpusdir, '.*') 

UWAGA: że PlaintextCorpusReader użyje domyślne nltk.tokenize.sent_tokenize() i nltk.tokenize.word_tokenize() dzielą twoje teksty na zdania i słowa, a te funkcje są budowane dla języka angielskiego, może to być praca dla wszystkich Języki.

Oto pełny kod z tworzeniem TextFiles testowych i jak stworzyć korpus z NLTK i jak uzyskać dostęp do korpusu na różnych poziomach:

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]) 

Wreszcie, aby odczytać katalog tekstów i utworzyć NLTK corpus w innym języku, należy najpierw upewnić się, że masz python-wywoływalnym słowo tokenizacja i zdanie tokenizacja modułów, które zajmuje ciąg/wejście basestring i wywołuje takie wyjście:

>>> 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', '.'] 
+0

Dziękuję za wyjaśnienia. Jednak wiele języków jest obsługiwanych domyślnie. –

+0

Jeśli ktoś otrzyma błąd "AttributeError: __exit__". Użyj 'open()' zamiast 'with()' –

+0

@TasdikRahman możesz uszczegółowić? Nie mogę przejść przez to ... – yashhy

Powiązane problemy