在大文本文件中使用 nltk 进行句子分割
Sentence segmentation using nltk in big text files
我需要使用 nltk.sent_tokenize()
从大文本文件中提取句子。文件大小从 1MB 到 400MB 不等,因此由于内存限制,不可能完全加载文件,我认为不可能使用 nltk.sent_tokenize()
并逐行读取文件。
你对完成这个任务有什么建议?
流式传输文件并在逐行阅读文件时对其进行处理。
如果用于存储令牌的内存有问题,则逐行或分批写入进程令牌。
一行一行:
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 个):
from __future__ import print_function
from nltk import word_tokenize
with open('input.txt', 'r') as fin, open('output.txt', 'w') as fout:
processed_lines = []
for i, line in enumerate(fin):
tokenized_line = ' '.join(word_tokenize(line.strip()))
processed_lines.append(tokenized_line)
if i % 1000 = 0:
print('\n'.join(processed_lines), end='\n', file=fout)
processed_lines = []
你试过只使用 reader 吗? nltk
语料库 reader 旨在递增地传递文本,在后台从磁盘读取大块而不是整个文件。因此,只需在你的整个语料库上打开一个 PlaintextCorpusReader
,它应该会逐句传递你的整个语料库,而不会出现任何恶作剧。例如:
reader = nltk.corpus.reader.PlaintextCorpusReader("path/to/corpus", r".*\.txt")
for sent in reader.sents():
if "shenanigans" in sent:
print(" ".join(sent))
我需要使用 nltk.sent_tokenize()
从大文本文件中提取句子。文件大小从 1MB 到 400MB 不等,因此由于内存限制,不可能完全加载文件,我认为不可能使用 nltk.sent_tokenize()
并逐行读取文件。
你对完成这个任务有什么建议?
流式传输文件并在逐行阅读文件时对其进行处理。
如果用于存储令牌的内存有问题,则逐行或分批写入进程令牌。
一行一行:
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 个):
from __future__ import print_function
from nltk import word_tokenize
with open('input.txt', 'r') as fin, open('output.txt', 'w') as fout:
processed_lines = []
for i, line in enumerate(fin):
tokenized_line = ' '.join(word_tokenize(line.strip()))
processed_lines.append(tokenized_line)
if i % 1000 = 0:
print('\n'.join(processed_lines), end='\n', file=fout)
processed_lines = []
你试过只使用 reader 吗? nltk
语料库 reader 旨在递增地传递文本,在后台从磁盘读取大块而不是整个文件。因此,只需在你的整个语料库上打开一个 PlaintextCorpusReader
,它应该会逐句传递你的整个语料库,而不会出现任何恶作剧。例如:
reader = nltk.corpus.reader.PlaintextCorpusReader("path/to/corpus", r".*\.txt")
for sent in reader.sents():
if "shenanigans" in sent:
print(" ".join(sent))