2011-02-09 21 views
62

Ho calcolato che spesso la risposta al mio titolo è di andare a leggere le documentazioni, ma mi sono imbattuto nel numero NLTK book ma non ho dato la risposta. Sono un po 'nuovo per Python.Creazione di un nuovo corpus con NLTK

Ho un mucchio di file .txt e voglio essere in grado di utilizzare le funzioni corpus fornite da NLTK per il corpus nltk_data.

ho provato PlaintextCorpusReader ma non ho potuto ottenere oltre:

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

Come fare segmento I le newcorpus frasi usando Punkt? Ho provato a utilizzare le funzioni punkt ma le funzioni punkt non sono state in grado di leggere la classe PlaintextCorpusReader?

Potete anche indicarmi come posso scrivere i dati segmentati in file di testo?

Modifica: Questa domanda ha avuto una ricompensa una volta e ora ha una seconda taglia. Vedi il testo nella casella di taglie.

risposta

32

Penso che lo PlaintextCorpusReader segmenti già l'input con un tokenizer punkt, almeno se la lingua di input è l'inglese.

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

È possibile passare al lettore una parola e la frase tokenizer, ma per questi ultimi il default è già nltk.data.LazyLoader('tokenizers/punkt/english.pickle').

Per una stringa singola, verrà utilizzato un tokenizzatore come segue (spiegato here, vedere la sezione 5 per il tokenizzatore punkt).

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

grazie per la spiegazione. Fatto. ma come faccio ad emettere le frasi segmentate in un file txt separato? – alvas

+0

Errore di entrambi i link, 404. Qualche dolce anima può aggiornare i collegamenti? – mtk

+0

Risolto il primo collegamento. Non ho idea di quale documento il secondo indicasse. – 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

Riprende alcuni problemi con la lingua devnagari. – ashim888

44

Dopo alcuni anni di capire come funziona, ecco il tutorial aggiornato dei

Come creare un corpus NLTK con una directory di file di testo?

L'idea principale è di utilizzare il pacchetto nltk.corpus.reader. Nel caso in cui si disponga di una directory di file di testo in inglese, è preferibile utilizzare lo PlaintextCorpusReader.

Se si dispone di una directory che assomiglia a questo:

newcorpus/ 
     file1.txt 
     file2.txt 
     ... 

semplicemente utilizzare queste righe di codice e si può ottenere un corpus:

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

corpusdir = 'newcorpus/' # Directory of corpus. 

newcorpus = PlaintextCorpusReader(corpusdir, '.*') 

NOTA: che il PlaintextCorpusReader useranno il valore predefinito nltk.tokenize.sent_tokenize() e nltk.tokenize.word_tokenize() per dividere i testi in frasi e parole e queste funzioni sono compilate per l'inglese, potrebbe essere NON lavoro per tutti le lingue.

Ecco il codice completo con la creazione di file di testo di prova e come creare un corpus con NLTK e modalità di accesso al corpus a diversi livelli:

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

Infine, per leggere un elenco di testi e creare un NLTK corpus in un altro lingue, è necessario innanzitutto assicurarsi di avere un parola tokenizzazione python-callable e frase tokenizzazione moduli che si stringa/ingresso basestring e produce come output:

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

Grazie per il chiarimento. Molte lingue sono supportate di default, però. –

+0

Se qualcuno riceve un errore "AttributeError: __exit__'. Usa 'open()' invece di 'con()' –

+0

@TasdikRahman puoi elaborare per favore? Non posso passare attraverso questo .. – yashhy

Problemi correlati