gpt4 book ai didi

python-3.x - 将文件拆分为 block

转载 作者:行者123 更新时间:2023-12-03 13:05:18 25 4
gpt4 key购买 nike

我正在尝试拆分格式为:

@some 
@garbage
@lines
@target G0.S0
@type xy
-0.108847E+02 0.489034E-04
-0.108711E+02 0.491023E-04
-0.108574E+02 0.493062E-04
-0.108438E+02 0.495075E-04
-0.108302E+02 0.497094E-04
....Unknown line numbers...
&
@target G0.S1
@type xy
-0.108847E+02 0.315559E-04
-0.108711E+02 0.316844E-04
-0.108574E+02 0.318134E-04
....Unknown line numbers...
&
@target G1.S0
@type xy
-0.108847E+02 0.350450E-04
-0.108711E+02 0.351669E-04
-0.108574E+02 0.352908E-04
&
@target G1.S1
@type xy
-0.108847E+02 0.216396E-04
-0.108711E+02 0.217122E-04
-0.108574E+02 0.217843E-04
-0.108438E+02 0.218622E-04
@target Gx.Sy组合是唯一的,每组数据总是由 & 终止.

我设法将文件分成块:
#!/usr/bin/env python3
import os
import sys
import itertools as it
import numpy as np
import matplotlib.pyplot as plt

try:
filename = sys.argv[1]
print(filename)
except IndexError:
print("ERROR: Required filename not provided")

with open(filename, "r") as f:
for line in f:
if line.startswith("@target"):
print(line.split()[-1].split("."))

x=[];y=[]
with open(filename, "r") as f:
for key,group in it.groupby(f,lambda line: line.startswith('@target')):
print(key)
if not key:
group = list(group)
group.pop(0)
# group.pop(-1)
print(group)
for i in range(len(group)):
x.append(group[i].split()[0])
y.append(group[i].split()[1])
nx=np.array(x)
ny=np.array(y)

我有两个问题:

1)真实数据之前的前导码行也被分组,所以如果有任何前导码,脚本将不起作用。无法预测会有多少行;但我想分组 @target

2)我想将数组命名为 G0[S0,S0] 和 G1[S1,S2];但我不能这样做。

请帮助

更新 :
我试图将这些数据存储在 G0[S0,S1,...], G1[S0,S1,...] 的嵌套 np 数组中,以便我可以在 matplotlib 中使用它。

最佳答案

这是使用生成器和 np.genfromtxt 的方法.优点:内存轻。它即时过滤文件,因此不需要将整个内容加载到内存中进行处理。

更新:

我简化了代码并将输出格式更改为数组数组。
如果例如 G范围介于 0...3 之间和 S范围介于 0...5 之间然后它创建一个包含数组的 4x6 数组。

import numpy as np
from itertools import dropwhile, groupby
from operator import itemgetter

def load_chunks(f):
f = open(f, 'rt') if isinstance(f, str) else f
f = filter(lambda l: not l.strip() in ("", "&"), f)
tok = "@target", "@type"
fg = dropwhile(itemgetter(0), groupby(f, lambda l: not l.split()[0] in tok))
I, D = [], []
for k, g in fg:
info = next(l.split() for l in g)[1]
I.append([int(key[1:]) for key in info.split('.')])
D.append(np.genfromtxt((l.encode() for l in next(fg)[1])))
G, S = np.array(I).T
res = np.empty((np.max(G)+1, np.max(S)+1), dtype=object)
res[G, S] = D
return res

fn = <your_file_name>

ara = load_chunks(fn)

关于python-3.x - 将文件拆分为 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42400552/

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