在Python中,如何保存文件中的数据而不是变量或列表中的数据?
我需要读取一个大约5 GB的文件,并用Python编写一个脚本,以实现这一点:在Python中,如何保存文件中的数据而不是变量或列表中的数据?,python,linux,bash,shell,unix,Python,Linux,Bash,Shell,Unix,我需要读取一个大约5 GB的文件,并用Python编写一个脚本,以实现这一点: cat file | awk -F '","' '{if ($12 !="" ) print $9,$10,$12}'| sort -n | uniq -c | sort -nr | head -100 9,10,12是我想要从该文件中获取的参数 我可以在Bash中毫无问题地完成它,在Python脚本中使用os.system和该命令。。。但是我需要正确地编写Python脚本 问题是我无法将数据保存在任何列表或变
cat file | awk -F '","' '{if ($12 !="" ) print $9,$10,$12}'| sort -n | uniq -c | sort -nr | head -100
9,10,12是我想要从该文件中获取的参数
我可以在Bash中毫无问题地完成它,在Python脚本中使用os.system和该命令。。。但是我需要正确地编写Python脚本
问题是我无法将数据保存在任何列表或变量中,因为脚本将在服务器上运行,由于文件的大小,无法使用如此大的RAM
我想把数据写入一个文件而不是一个列表,但我还没有找到一种方法。我不确定这是否是你想要的,但如果你把它与其他用户建议的文本划分结合起来,也许会有所帮助 您可以将数据保存在.txt文件中,如下所示:
file = open("path/file.txt", "w") # This will create the file.
write = file.write(text_variable) # This will write the content of text_variable into your file.txt
file.close()
还有另一种方法,即使用JSON:
import json
text = json.dumps(text_variable) # This will store the content of text_variable in a json format.
file = open("path/file.json", "w") # This will create the json file.
write = file.write(text) # This will write the content of text into your file.json
file.close()
然后,如果要获取JSON的数据,只需执行以下操作:
import json
file = open("path/file.json", "r") # This will open the json file in read mode.
jsontext = file.read()
text = json.loads(jsontext) # You will have in text the original data you had at the beginning.
我希望它能有所帮助。您至少可以使用一个python变量 这可以优化三胞胎的存储和它们出现的次数 伪脚本:
for line in file.readlines():
data = line.strip().split(',')
x = data[colums_that_you_want]
xtoken = '_'.join(x)
counter[xtoken] += 1
counter.most_common(100)
仅出于教育目的,我想表明,这一行可以更有效地重写: 原件:
$ cat file | awk -F '","' '{if ($12 !="" ) print $9,$10,$12}'| sort -n | uniq -c | sort -nr | head -100
$ awk -F '","' '($12 !="" ){print $9,$10,$12}' file | sort -n | uniq -c | sort -nr | head -100
1。删除cat
:
$ cat file | awk -F '","' '{if ($12 !="" ) print $9,$10,$12}'| sort -n | uniq -c | sort -nr | head -100
$ awk -F '","' '($12 !="" ){print $9,$10,$12}' file | sort -n | uniq -c | sort -nr | head -100
几乎不需要使用cat
命令
$ awk -F '","' '{if ($12 !="" ) print $9,$10,$12}' file | sort -n | uniq -c | sort -nr | head -100
2。改善awkawk
:
$ cat file | awk -F '","' '{if ($12 !="" ) print $9,$10,$12}'| sort -n | uniq -c | sort -nr | head -100
$ awk -F '","' '($12 !="" ){print $9,$10,$12}' file | sort -n | uniq -c | sort -nr | head -100
3。消除sort-n | uniq-c
:您可以通过再次使用awk
来消除这两种情况。您将所有内容存储在一个数组中,但本质上这正是sort
和uniq
所做的
$ awk -F '","' '($12 !="" ){a[$9 OFS $10 OFS $12]++}
END{for(i in a) print a[i],i}' file | sort -nr | head -100
4。消除最后两个管道:使用GNU awk您可以使用PROCINFO
$ awk -F '","' 'BEGIN{PROCINFO["sorted_in"] = "@val_num_desc"}
($12 !="" ){a[$9 OFS $10 OFS $12]++}
END{for(i in a) {j++; print a[i],i; if (j==100) exit} }' file
如果不能使用太多内存,请使用中间文件。这将需要更长的时间,但它会起作用。你为什么没有达到这个目的?问题是什么?向我们展示您尝试过的代码,以便我们能够查明问题所在。