Чтение текста корпуса с помощью nltk.corpus.reader.plaintext - Python 3 [duplicate]

Самое простое решение - создать функцию JavaScript и вызвать его для обратного вызова Ajax success.

function callServerAsync(){
    $.ajax({
        url: '...',
        success: function(response) {

            successCallback(response);
        }
    });
}

function successCallback(responseObj){
    // Do something like read the response and show data
    alert(JSON.stringify(responseObj)); // Only applicable to JSON response
}

function foo(callback) {

    $.ajax({
        url: '...',
        success: function(response) {
           return callback(null, response);
        }
    });
}

var result = foo(function(err, result){
          if (!err)
           console.log(result);    
}); 
70
задан projectdp 22 January 2015 в 00:16
поделиться

3 ответа

Я думаю, что PlaintextCorpusReader уже сегментирует вход с токенизатором punkt, по крайней мере, если ваш язык ввода является английским.

Конструктор 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').

Для одной строки токенизатор будет использоваться следующим образом (пояснил здесь , см. раздел 5 для токенатора 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())
36
ответ дан alexis 24 August 2018 в 10:20
поделиться

После нескольких лет выяснения, как это работает, вот обновленный учебник

Как создать корпус 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(), чтобы разделить ваши тексты на предложения и слова, и эти функции построены для английского языка, он НЕ МОЖЕТ работать для всех языков.

полный код с созданием тестовых текстовых файлов и как создать корпус с 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-callable токенизация слова и модули токенизации предложения, которые принимают ввод string / basestring и создают такой вывод:

>>> 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', '.']
51
ответ дан alvas 24 August 2018 в 10:20
поделиться
 >>> 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')
9
ответ дан Uli Köhler 24 August 2018 в 10:20
поделиться
Другие вопросы по тегам:

Похожие вопросы: