2 回答
TA貢獻1794條經驗 獲得超8個贊
嘗試:
bert = [json.loads(line)['features'][0]['layers'][0]['values'] for line in f]
這樣,您至少不會一次讀取內存中的整個文件-也就是說,如果文件很大,您必須進一步處理存儲的內容bert
TA貢獻1788條經驗 獲得超4個贊
我在搜索類似問題時找到了這個解決方案。它不是在特定問題中投票最多的,但在我看來,它比任何東西都好。
這個想法很簡單:不是保存一個字符串列表(文檔中的每一行一個),而是保存一個引用每一行的文件索引位置列表,然后當你想訪問它的內容時,你只需要seek到這個記憶位置。為此,一個類LineSeekableFile就派上用場了。
唯一的問題是您需要在整個過程中保持文件對象(而不是整個文件?。┐蜷_。
class LineSeekableFile:
def __init__(self, seekable):
self.fin = seekable
self.line_map = list() # Map from line index -> file position.
self.line_map.append(0)
while seekable.readline():
self.line_map.append(seekable.tell())
def __getitem__(self, index):
# NOTE: This assumes that you're not reading the file sequentially.
# For that, just use 'for line in file'.
self.fin.seek(self.line_map[index])
return self.fin.readline()
然后訪問它:
b_file = bert_dir+"/output4layers.json"
fin = open(b_file, "rt")
BertSeekFile = LineSeekableFile(fin)
b_line = BertSeekFile[idx] #uses the __getitem__ method
fin.close()
添加回答
舉報
