大文本文件中基于nltk的句子分割

2024-04-26 04:55:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要使用nltk.sent_tokenize()从大文本文件中提取句子。文件大小从1MB到400MB不等,因此完全由于内存限制无法加载文件,我认为不可能使用nltk.sent_tokenize()逐行读取文件。在

你建议怎么做这个任务?在


Tags: 文件内存建议句子sent文本文件tokenizenltk
2条回答

你试过用读卡器吗?nltk语料库读取器被设计成以增量方式传递文本,从后台的磁盘读取大的块,而不是整个文件。所以只要在你的整个语料库上打开一个PlaintextCorpusReader,它就应该一句一句地传达你的整个语料库,而不是任何恶作剧。例如:

reader = nltk.corpus.reader.PlaintextCorpusReader("path/to/corpus", r".*\.txt")
for sent in reader.sents():
    if "shenanigans" in sent:
        print(" ".join(sent))

流式处理文件,并在逐行读取文件时进行处理。在

如果存储令牌的内存是个问题,那么逐行或成批地写出进程令牌。在

逐行:

from __future__ import print_function
from nltk import word_tokenize
with open('input.txt', 'r') as fin, open('output.txt', 'w') as fout:
    for line in fin:
        tokenized_line = ' '.join(word_tokenize(line.strip()))
        print(tokenized_line, end='\n', file=fout)

分批(共1000个):

^{pr2}$

相关问题 更多 >