gpt4 book ai didi

python - Python处理大量数据的方法

转载 作者:行者123 更新时间:2023-11-28 20:44:08 25 4
gpt4 key购买 nike

我有一个包含大量数据 (3 GB) 的文本文件。此文本文件的每一行都包含时间、源 IP、目标 IP 和大小。如您所知,IP 地址最后一部分的数字显示端口地址。我想将这些端口地址带到我为 10 000 行数据绘制的直方图中,但正如我猜测的那样,Python 代码无法针对如此大量的数据执行。我简单解释一下我写的代码。首先,我读取了 10 000 个数据点,然后将它们拆分并全部放入名为 everything_list 的列表中。只需忽略 while 循环起作用的条件。后来我把所有的端口地址放在一个列表中,并绘制了这些的直方图。现在假设我有一百万条数据线,我一开始就无法阅读它们,更不用说对它们进行分类了。有些人告诉我使用数组,有些人告诉我先处理一大块数据,然后再处理另一 block 数据。我对所有人所说的感到困惑。有人可以帮我解决这个问题吗?

text_file = open("test.data", "r")
a = text_file.read()
text_file.close()

everything_list = a.split()
source_port_list = []
i=0
while 6+7*i<len(everything_list):

source_element = everything_list[2+7*i]
source_port_position = source_element.rfind('.')
source_port_number = int(source_element[source_port_position + 1:])
source_port_list.append(source_port_number)

i=i+1


import matplotlib.pyplot as plt
import pylab


numBins = 20
plt.hist(source_port_list, numBins, color='red', alpha=0.8)
plt.show()

这是行格式:

15:42:42.719063 IP 129.241.138.133.47843 > 129.63.27.12.2674: tcp 1460
15:42:42.719205 IP 129.241.138.133.47843 > 129.63.27.12.2674: tcp 1460
15:42:42.719209 IP 129.63.57.175.45241 > 62.85.5.142.55455: tcp 0
15:42:42.719213 IP 24.34.41.8.1236 > 129.63.1.23.443: tcp 394
15:42:42.719217 IP 59.167.148.152.25918 > 129.63.57.40.36075: tcp 0
15:42:42.719260 IP 129.63.223.16.2823 > 80.67.87.25.80: tcp 682
15:42:42.719264 IP 129.63.184.118.2300 > 64.111.215.46.80: tcp 0
15:42:42.719269 IP 129.63.184.118.2300 > 64.111.215.46.80: tcp 0

最佳答案

我不知道数据是什么样的,但我认为问题在于您试图一次将所有数据保存在内存中。你需要一点一点地做,read the lines one by one并构建直方图。

histogram = {}
with open(...) as f:
for line in f:
ip = ...
if ip in histogram:
histogram[ip] += 1
else:
histogram[ip] = 1

您现在可以绘制直方图,但使用 plt.plot 而不是 plt.hist 因为您已经在 histogram 字典中有了频率.

关于python - Python处理大量数据的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27672459/

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