[英]Python parsing a huge file
我正在尋找有效的方法來加載一個包含數據的大文件。
該文件具有以下格式
1\\tword1\\tdata
2\\tword2\\tdata
3\\tword3\\tdata
\\r\\n
1\\tword4\\tdata
2\\tword2\\tdata
\\r\\n
其中\\r\\n
定義由單詞組成的句子的結尾。
我有興趣加載文件和保存結構,即我想引用句子和句子中的單詞,一般作為結果我想得到這樣的東西
data = [sentence1, sentence2,... ]
其中sentence = [word1,word2,...]
逐行加載文件需要花費大量時間,批量加載文件效率更高,但我不知道如何解析和分割數據到句子。
目前我使用以下代碼
def loadf(filename):
n = 100000
data = []
with open(filename) as f:
while True:
next_n_lines = list(islice(f, n))
if not next_n_lines:
break
data.extend([line.strip().split('\t') for line in next_n_lines])
使用此代碼我不知道如何將數據划分為句子,此外我懷疑extend
實際上不會擴展當前列表但創建一個新列表並重新分配,因為它非常慢。
我將不勝感激任何幫助。
怎么樣:
import csv
from itertools import groupby
with open(yourfile) as fin:
tabin = csv.reader(fin, delimiter='\t')
sentences = [[el[1] for el in g] for k, g in groupby(tabin, bool) if k]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.