2011-02-09 54 views
62

Tôi cho rằng câu trả lời cho tiêu đề của tôi thường là đọc và đọc các tài liệu, nhưng tôi đã chạy qua số NLTK book nhưng không đưa ra câu trả lời. Tôi là loại mới với python.Tạo một kho văn bản mới với NLTK

Tôi có một bó các tệp .txt và tôi muốn có thể sử dụng các chức năng văn bản mà NLTK cung cấp cho kho dữ liệu nltk_data.

Tôi đã thử PlaintextCorpusReader nhưng tôi không thể có được xa hơn:

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

Làm thế nào để phân khúc newcorpus câu sử dụng punkt? Tôi đã cố gắng sử dụng các chức năng punkt nhưng các chức năng punkt không thể đọc được lớp học PlaintextCorpusReader?

Bạn cũng có thể dẫn tôi đến cách tôi có thể ghi dữ liệu được phân đoạn vào tệp văn bản không?

Chỉnh sửa: Câu hỏi này có tiền thưởng một lần và giờ đây có tiền thưởng thứ hai. Xem văn bản trong hộp tiền thưởng.

Trả lời

32

Tôi nghĩ rằng PlaintextCorpusReader đã phân đoạn đầu vào bằng bộ mã hóa punkt, ít nhất nếu ngôn ngữ nhập liệu của bạn là tiếng Anh.

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

Bạn có thể vượt qua người đọc một từ và câu tokenizer, nhưng đối với sau này mặc định đã là nltk.data.LazyLoader('tokenizers/punkt/english.pickle').

Đối với một chuỗi đơn, trình mã thông báo sẽ được sử dụng như sau (được giải thích here, xem phần 5 dành cho trình mã hóa 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

cảm ơn lời giải thích. Hiểu rồi. nhưng làm cách nào để xuất các câu được phân đoạn vào một tệp txt được phân tách? – alvas

+0

Cả hai liên kết đều bị lỗi, 404. Có thể một số linh hồn ngọt ngào cập nhật liên kết không? – mtk

+0

Cố định liên kết đầu tiên. Không có ý tưởng gì tài liệu thứ hai được sử dụng để trỏ đến. – 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

Bắn một số vấn đề cho ngôn ngữ devnagari. – ashim888

44

Sau vài năm tìm hiểu làm thế nào nó hoạt động, đây là cập nhật hướng dẫn của

Làm thế nào để tạo ra một corpus với một thư mục của textfiles NLTK?

Ý tưởng chính là sử dụng gói nltk.corpus.reader. Trong trường hợp bạn có một thư mục các tệp văn bản trong tiếng Anh, tốt nhất bạn nên sử dụng số PlaintextCorpusReader.

Nếu bạn có một thư mục đó trông như thế này:

newcorpus/ 
     file1.txt 
     file2.txt 
     ... 

Đơn giản chỉ cần sử dụng các dòng mã và bạn có thể nhận được một corpus:

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

corpusdir = 'newcorpus/' # Directory of corpus. 

newcorpus = PlaintextCorpusReader(corpusdir, '.*') 

LƯU Ý: rằng PlaintextCorpusReader sẽ sử dụng mặc định nltk.tokenize.sent_tokenize()nltk.tokenize.word_tokenize() để chia văn bản của bạn thành câu và từ và các chức năng này được xây dựng cho tiếng Anh, có thể NOT hoạt động cho tất cả ngôn ngữ.

Dưới đây là đoạn code đầy đủ với sự sáng tạo của textfiles kiểm tra và làm thế nào để tạo ra một corpus với NLTK và làm thế nào để truy cập corpus ở các cấp khác nhau:

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

Cuối cùng, để đọc một thư mục các văn bản và tạo ra một NLTK corpus bằng các ngôn ngữ khác, trước tiên bạn phải đảm bảo rằng bạn có một con trăn-callable từ tokenizationcâu tokenization module mất chuỗi/basestring đầu vào và sản lượng sản xuất như:

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

Cảm ơn bạn đã làm rõ. Mặc dù vậy, nhiều ngôn ngữ được hỗ trợ theo mặc định. –

+0

Nếu có ai nhận được lỗi 'AttributeError: __exit__'. Sử dụng 'open()' thay vì 'with()' –

+0

@TasdikRahman bạn có thể xây dựng không? Tôi không thể vượt qua điều này .. – yashhy

Các vấn đề liên quan