gpt4 book ai didi

python - 在 4GB 文件上运行 python 脚本时出现内存错误

转载 作者:行者123 更新时间:2023-11-30 22:13:57 25 4
gpt4 key购买 nike

我正在尝试计算长度在 1 到 5 之间的单词数,文件大小约为 4GB,最终出现内存错误。

import os 
files = os.listdir('C:/Users/rram/Desktop/')
for file_name in files:
file_path = "C:/Users/rram/Desktop/"+file_name
f = open (file_path, 'r')
text = f.readlines()
update_text = ''
wordcount = {}
for line in text:
arr = line.split("|")
word = arr[13]
if 1<=len(word)<6:
if word not in wordcount:
wordcount[word] = 1
else:
wordcount[word] += 1
update_text+= '|'.join(arr)
print (wordcount) #print update_text
print 'closing', file_path, '\t', 'total files' , '\n\n'
f.close()

最后我在这一行得到一个MemoryError text = f.readlines()

请您帮忙优化一下。

最佳答案

正如评论中所建议的,您应该逐行阅读文件,而不是整个文件。

例如:

count = 0
with open('words.txt','r') as f:
for line in f:
for word in line.split():
if(1 <= len(word) <=5):
count=count+1
print(count)

编辑:

如果您只想计算第 14 列中的单词数并按 | 分割,则:

count = 0
with open('words.txt','r') as f:
for line in f:
iterator = 0
for word in line.split("|"):
if(1 <= len(word) <=5 and iterator == 13):
count=count+1
iterator = iterator +1
print(count)

请注意,您应该避免这样写

arr = line.split("|")
word = arr[13]

因为该行包含的单词可能少于 14 个,这可能会导致段错误。

关于python - 在 4GB 文件上运行 python 脚本时出现内存错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50639222/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com