数据分析--Python读取大型文本文件
数据分析-Python读取大型文本文件
在数据分析中 有时数据源会是超大的文本文件(几G,或在几十G),需要从中提取需要的信息 如果用普通方法进行遍历查找 效率非常低 使用mmap库进行查找 效率会非常高 几G的内容 完全搜索 也只需要几分钟时间
import mmap
import pandas as pd
def mm_find(file, sub, bf_offset=0, af_offset=0):
"""
搜索文件中所有的字符串sub, 并返回所有匹配的位置loc - bf_offset:loc + af_offset的数据,
loc是匹配sub的字节位置
Args:
file: 文件对象
sub: 要搜索的字符串
bf_offset: 相对于匹配的字节位置的向前偏移量
af_offset: 相对于匹配的字节位置的向后偏移量
Returns:
"""
s = mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ)
re = []
st = 0
while True:
loc = s.find(bytes(sub, encoding='utf8'), st)
if loc == -1:
break
re.append(str(s[loc - bf_offset:loc + af_offset], encoding='utf8'))
st = loc + af_offset + 1
return re
def mm_find_line(file, sub):
"""
搜索文件中所有的字符串sub, 并返回所有匹配的sub所在行的内容
Args:
file: 文件对象
sub: 要搜索的字符串
Returns:
"""
s = mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ)
re = []
sub = bytes(sub, encoding='utf8')
while True:
l = s.readline()
if not l:
break
if sub in l:
re.append(str(l, encoding='utf8'))
return re
def main():
fx = '/home/john/Downloads/data/0418/log_fps_delay/041803log'
file = open(fx, "r")
data = mm_find(file, 'FPS', 71, 11)
pd.DataFrame(data).to_csv('../../../assets/fps_delay_cpu_mem/0418/fps_delay/ls.csv')
print(data)
if __name__ == '__main__':
main()