我的 .txt 檔案中有資料,如下所示(讓我們將其命名為“myfile.txt”):
28807644'~'0'~'Maun FCU'~'US#@#@#28855353'~'0'~'WNB Holdings LLC'~'US#@#@#29212330'~'0'~'愛達荷第一銀行'~'US#@#@#29278777'~'0'~'亞利桑那共和國銀行'~'US#@#@#29633181'~'0'~'Friendly Hills Bank'~'US#@#@# 29760145'~'0'~'弗吉尼亞自由銀行'~'US#@#@#100504846'~'0'~'Community First Fund Federal Credit Union'~'US#@#@#
我嘗試了幾種方法來將此 .txt 轉換為 .csv,其中一種方法是使用 CSV 庫,但由于我非常喜歡 Panda,因此我使用了以下內容:
import pandas as pd
import time
#time at the start of program is noted
start = time.time()
# We set the path where our file is located and read it
path = r'myfile.txt'
f = open(path, 'r')
content = f.read()
# We replace undesired strings and introduce a breakline.
content_filtered = content.replace("#@#@#", "\n").replace("'", "")
# We read everything in columns with the separator "~"
df = pd.DataFrame([x.split('~') for x in content_filtered.split('\n')], columns = ['a', 'b', 'c', 'd'])
# We print the dataframe into a csv
df.to_csv(path.replace('.txt', '.csv'), index = None)
end = time.time()
#total time taken to print the file
print("Execution time in seconds: ",(end - start))
這需要大約 35 秒來處理,是一個 300MB 的檔案,我可以接受這種型別的性能,但我正在嘗試對一個更大的檔案執行相同的操作,該檔案的大小為 35GB 并且它會產生一條 MemoryError 訊息。
我嘗試使用 CSV 庫,但結果相似,我嘗試將所有內容放入串列,然后將其寫入 CSV:
import csv
# We write to CSV
with open(path.replace('.txt', '.csv'), "w") as outfile:
write = csv.writer(outfile)
write.writerows(split_content)
結果是相似的,不是很大的改進。有什么方法或方法可以將非常大的 .txt 檔案轉換為 .csv 嗎?可能超過 35GB?
我很樂意閱讀您的任何建議,提前致謝!
uj5u.com熱心網友回復:
由于您的代碼只是直接替換,因此您可以按順序讀取所有資料并隨時檢測需要替換的部分:
def process(fn_in, fn_out, columns):
new_line = b'#@#@#'
with open(fn_out, 'wb') as f_out:
# write the header
f_out.write((','.join(columns) '\n').encode())
i = 0
with open(fn_in, "rb") as f_in:
while (b := f_in.read(1)):
if ord(b) == new_line[i]:
# keep matching the newline block
i = 1
if i == len(new_line):
# if matched entirely, write just a newline
f_out.write(b'\n')
i = 0
# write nothing while matching
continue
elif i > 0:
# if you reach this, it was a partial match, write it
f_out.write(new_line[:i])
i = 0
if b == b"'":
pass
elif b == b"~":
f_out.write(b',')
else:
# write the byte if no match
f_out.write(b)
process('my_file.txt', 'out.csv', ['a', 'b', 'c', 'd'])
這樣做很快。您可以通過分塊讀取來提高性能,但這仍然非常快。
這種方法比你的方法有優勢,它在記憶體中幾乎沒有任何內容,但它幾乎沒有優化快速讀取檔案。
編輯:在邊緣情況下有一個大錯誤,我在重新閱讀后意識到,現在修復了。
uj5u.com熱心網友回復:
我拿了你的示例字串,并通過將該字串乘以 1 億(類似your_string*1e8......)來制作一個示例檔案,以獲得一個 31GB 的測驗檔案。
按照@Grismar 的分塊建議,我做了以下內容,它在大約 2 分鐘內處理 31GB 檔案,峰值 RAM 使用量取決于塊大小。
復雜的部分是跟蹤欄位和記錄分隔符,它們是多個字符,肯定會跨越一個塊,因此被截斷。
我的解決方案是檢查每個塊的末尾,看看它是否有部分分隔符。如果是,則從當前塊的末尾洗掉該部分,寫出當前塊,并且該部分成為下一個塊的開始(并且應該由其完成):
CHUNK_SZ = 1024 * 1024
FS = "'~'"
RS = '#@#@#'
# With chars repeated in the separators, check most specific (least ambiguous)
# to least specific (most ambiguous) to definitively catch a partial with the
# fewest number of checks
PARTIAL_RSES = ['#@#@', '#@#', '#@', '#']
PARTIAL_FSES = ["'~", "'"]
ALL_PARTIALS = PARTIAL_FSES PARTIAL_RSES
f_out = open('out.csv', 'w')
f_out.write('a,b,c,d\n')
f_in = open('my_file.txt')
line = ''
while True:
# Read chunks till no more, then break out
chunk = f_in.read(CHUNK_SZ)
if not chunk:
break
# Any previous partial separator, plus new chunk
line = chunk
# Check end-of-line for a partial FS or RS; only when separators are more than one char
final_partial = ''
if line.endswith(FS) or line.endswith(RS):
pass # Write-out will replace complete FS or RS
else:
for partial in ALL_PARTIALS:
if line.endswith(partial):
final_partial = partial
line = line[:-len(partial)]
break
# Process/write chunk
f_out.write(line
.replace(FS, ',')
.replace(RS, '\n'))
# Add partial back, to be completed next chunk
line = final_partial
# Clean up
f_in.close()
f_out.close()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/372795.html
上一篇:需要有關使用R清理資料的建議
