Python 如何在单个文本文件中使用多个事件循环?
我是一名编程新手。我在单个文本文件(data.txt)中有多个事件(超过1000个事件)。比如说Python 如何在单个文本文件中使用多个事件循环?,python,plot,Python,Plot,我是一名编程新手。我在单个文本文件(data.txt)中有多个事件(超过1000个事件)。比如说 BoardID: 31 Channel: 1 Event Number: 3123 Pattern: 0x0000 2627.000000 2627.000000 2626.009033 2629.000000 . . .(up to 1024 data) BoardID: 31 Channel: 1 Event Number: 3124 Pattern: 0x0000 26
BoardID: 31
Channel: 1
Event Number: 3123
Pattern: 0x0000
2627.000000
2627.000000
2626.009033
2629.000000
.
.
.(up to 1024 data)
BoardID: 31
Channel: 1
Event Number: 3124
Pattern: 0x0000
2627.000000
2627.000000
2628.949707
2626.099365
.
.
....(up to 1024 data)
.
..1000 number of events
如何使用多个事件上的循环逐个绘制所有数据
我正在尝试以下python代码,但它不起作用:
with open("data.txt") as f:
for i in range(1000): #I have 1000 number of events
all_lines = f.readlines()
def plot_event(start = 4, all_lines= 'all_lines'):
lines = all_lines[start : 1029 - 4 + start]
return (plot_event(4*i, all_lines))
x = np.array(range(1,1025)) #for all the events x has same range
y2 = float(lines.split()[0])
y2_=list(y2)
y22 = [((j / 4096)-0.5) for j in y2_]
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlabel('Time (ns)')
ax.set_ylabel('counts')
ax.plot(x,y22, 'k-', color= 'b', label='data')
fig=plt.gcf()
plt.show()
plt.draw()
有人能解释一下如何使用循环一个接一个地绘制每个事件吗?您的代码大部分都是正确的,只是缩进和排序有一些问题 您尝试以1000倍的速度读取整个文件,但在第一次到达文件末尾后却什么也没有得到 此外,绘图应在循环内
# read in the file. We only need to do this once
with open('data.txt') as f:
all_lines = [line for line in f]
define x outside of the loop. Numpy has a range generating function. Use that
x = np.arange(1,1025)
# loop through each event
for start in range(1000):
# get data points
# each event has values at 1028*start:1028*(start+1), but we don't need the first 4 values
# defining y2 as an array automatically handles the float conversion
# also makes the math easier
y2 = np.array(all_lines[1028*start+4:1028*(start+1)],dtype=float)
y22 = y2 / 4096 - .5
# plot stuff. I just copies your code here
# only change was putting it in the loop
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlabel('Time (ns)')
ax.set_ylabel('counts')
ax.plot(x,y22, 'k-', color='b', label='data')
fig = plt.gcf()
plt.show()
plt.draw()
谢谢David L,但是当我使用y2=np.array(所有行[1029*start+4:1029*(start+1)],dtype=float)时,我得到了ValueError:无法将字符串转换为float:Pattern:0x0000。当我使用y2=np.array(所有行[1029*start+4:1029*(start)],dtype=float)时#我得到的y2是空的。有问题,抱歉。我从你的代码中复制了1029号,没有考虑它。将其更改为1028应该可以解决以下问题:您的数据是格式4标签(BoardID、channel、Event Number、Pattern),后跟1024行数字。如果每个事件的位数可能不同,则需要稍微修改代码