Extracting data and signals from a file
Before I start, I'm just a beginner here as well as Python and I'm working on something like extracting data from a file and then from data that I need to create a data signal. I don't know how to explain it, but I will try my best to explain the problem and here's what. I was given a text file like:
12 0011
15 001a
20 111e
32 8877
50 00f3
56 1000
I was able to read the files and put them into a dictionary:
def dictionary(filename):
d = {}
f = open(filename,'r')
for lines in f:
line = lines.split(' ',1)
line[1] = line[1].replace('\n','')
d[line[0]] = line[1]
f.close()
for k in sorted(d.keys()):
print 'Keys:', k, '-> Values:', d[k]
return d
Well for the second part it refers to a text file where the first column represents time and the second column represents data. This means that at time = 15 seconds, data 001a is incremented until time = 20 seconds, when data changes to 111e. The data remains unchanged (111e) until time = 32 s, where the data changes again to 8877. The same process continues. I had to extract the output produced from time = 15s to time = 60s in an interval of 1s per time. The problem is, I don't know the exact method for this part. I don't know how to go to the next key. I tried with enumerate(d)
but it pops up from AttributeError. I also tried d.iteritems().next()
but it goes into an infinite loop. Here is my code:
def output(d):
a = 0
keys = sorted(d.keys())
while a <= 45:
time = a + 15
for k in keys:
if time == k:
sig = d[k]
else:
while time != k:
k = d.iteritems().next()[0]
print 'Time:', time, '-> Signal:' sig
a += 1
Can anyone help me? Many thanks.
EDIT: For a better understanding, the expected output looks like this:
Time: 15s -> Signal: 001a
Time: 16s -> Signal: 001a
Time: 17s -> Signal: 001a
Time: 18s -> Signal: 001a
Time: 19s -> Signal: 001a
Time: 20s -> Signal: 111e
Time: 21s -> Signal: 111e
Time: 22s -> Signal: 111e
Time: 23s -> Signal: 111e
...
Time: 31s -> Signal: 111e
Time: 32s -> Signal: 8877
Time: 33s -> Signal: 8877
...
Time: 49s -> Signal: 8877
Time: 50s -> Signal: 00f3
Time: 51s -> Signal: 00f3
...
Time: 55s -> Signal: 00f3
Time: 56s -> Signal: 1000
Time: 57s -> Signal: 1000
... represents the time that is still running. This should show the data transition according to the text file above. Output signal reaches 60 seconds
source to share