hi,
assuming i have a file that contains below data:
cell Bit
0 1
1 X
2 1
3 0
4 X
5 X
6 X
7 X
8 1
9 X
10 0
11 0
12 X
13 X
14 1
15 1
how can i group every 4 bits into a row? for eg:
ROW1=01X1
ROW2=XXXX
ROW3=00X1
ROW4=11XX
i'm using Python 2.5, Win XP.
thanks
maximus
File object method readline() could be substituted for next(). If you don't have labels on the first line in the data file, leave out f.next().
10 2608 bvdet 2,851
Expert Mod 2GB
Here's one way: Open the file, assigning the object to an identifier. Initialize an empty list to contain the strings representing 4 bits and another list to contain the characters. Iterate on the file object using enumerate, skipping the first line. Append the last character of next four lines to the character list (using the modulo operator to determine when to do this), then join the character list and append it to the 4 bits list and reinitialize the character list. After the end of file is reached, close the file object and convert the list into a formatted string. It is simpler than it sounds. Give it a shot.
thanks. btw, do you have any advice on a better s/w to use to debug python script. i'm only using IDLE and sometimes i get traceback error and not sure how to debug it except to that line.
here's the code: -
def main():
-
-
new_rows = {}
-
values = []
-
-
f=open('test.txt')
-
for line in f:
-
-
values.append(line.rstrip('\n')[-1])
-
-
-
x = []
-
x += values
-
-
for count in xrange(len(values)/4):
-
temp_values = (x.pop(3))+(x.pop(2))+(x.pop(1))+(x.pop(0))
-
new_rows['ROW'+str(count+1)] = temp_values
-
print new_rows
-
-
if __name__ == '__main__':
-
main()
-
the code seems to give wrong result from what i expect.
result:
{'ROW1': '1X1 ', 'ROW2': 'XXX0', 'ROW3': '0X X', 'ROW4': '1XX0'}
but i'm expecting:
ROW1=01X1
ROW2=XXXX
ROW3=00X1
ROW4=11XX
pls advise. tq
bvdet 2,851
Expert Mod 2GB
I modified your function somewhat. Variable values and x contained the same data, so I eliminated x. A dictionary is unordered, so I changed new_rows to another list. I used range with a step of 4 and slicing to get the characters. I also skipped the first line, assuming the first line contains the column labels. - def main():
-
new_rows = []
-
values = []
-
f=open('test.txt')
-
f.next()
-
for line in f:
-
values.append(line.rstrip('\n')[-1])
-
f.close()
-
for count in xrange(0, len(values), 4):
-
new_rows.append(('ROW'+str((count/4)+1),values[count:count+4]))
-
print "\n".join(["%s=%s" % (item[0], "".join(item[1])) for item in new_rows])
-
-
-
if __name__ == '__main__':
-
main()
Here's the way I was suggesting: - f = open("test.txt")
-
f.next()
-
dataList = []
-
strList = []
-
for i, line in enumerate(f):
-
strList.append(line.strip().split()[1])
-
if not (i+1)%4:
-
dataList.append("".join(strList))
-
strList = []
-
f.close()
-
output = "\n".join(["ROW%s=%s" % (i+1, dataList[i]) for i in range(len(dataList))])
-
print output
sorry i didnt mention that i'm using Python 2.5 and Win XP. would like to check whether next() work for Python 2.5, i thought i read it somewhere it doesnt. anyway, i tried the code, it didnt complain any error. so i guess it works on Python 2.5 too..
i have a more complex data file as attached and i modified the code to be: -
f = open("test2.txt")
-
f.next()
-
dataList = []
-
strList = []
-
for i, line in enumerate(f):
-
strList.append(line.strip().split()[-1])
-
if not (i+1)%128:
-
dataList.append("".join(strList))
-
strList = []
-
f.close()
-
output = "\n".join(["ROW%s=%s" % (i+1, dataList[i]) for i in range(len(dataList))])
-
print output
-
and it seems to be working too. :)
bvdet 2,851
Expert Mod 2GB
File object method readline() could be substituted for next(). If you don't have labels on the first line in the data file, leave out f.next().
i notice the code extracts until 128x4=512. there are 8 characters being truncated. total there are 520. how do i resolve this? tq
bvdet 2,851
Expert Mod 2GB strList will contain data. Test for this condition and add to output as needed.
thanks for your advice. :)
Sign in to post your reply or Sign up for a free account.
Similar topics
by: David Elliott |
last post by:
I am trying to group data. I have a daily record that contains multiple projects and
multiple items in the project. I would like to roll the daily data into project 1 and all
the items that go...
|
by: Lee |
last post by:
I have a crosstab query that lists the number of patients(DECnum)by
County. County is my Row Heading. Currently, the Column heading is Age
in months, which is set at one month intervals. I would...
|
by: David |
last post by:
Hi,
I have a report for which each record is a product.
I have the fields: ProductName and GroupCode
There may be several variants on each ProductName, BUT, with the same
group code
i.e.
|
by: Amadelle |
last post by:
Hi All and thanks in advance,
I was wondering what is the best way of grouping data in a dataset. Like
using a "Group By" clause in Sql statements. I was thinking of using XML
but I don't even...
|
by: NuB |
last post by:
I have to create a datagrid that shows my data like this:
BMW
325i
325ci
525
Lexus
IS 300
GS
Mercedes
|
by: develguy |
last post by:
I am having trouble figuring this one out... Hopefully someone can
help!
I have a table ("tbl1")
It has five (5) fields:
1- "Item1"
2- "Item2"
3- "Item3"
4- "ScanImage" (stores scan...
|
by: John |
last post by:
On my gridview I need to group the sales by year.
2000 - 2001 - 2002, etc is there a way to do this with using the gridview?
example:
sales for: 2000
data
blank row
sales for: 2001
data...
|
by: renauddubert |
last post by:
Hi!
I have a table with 2 fields:
person_id and volume
the final goal is to be able to draw a graph in excel representing under X each person, and under Y the corresponding volume (after...
|
by: jehugaleahsa |
last post by:
Hello:
I have an XML file that contains records with a Date attribute. I
would like to group all the records together with a particular date,
so that I can later iterate over the different dates...
|
by: HowHow |
last post by:
First time using crosstab query because tired of creating queries and put them together in one query (such a stupid thing to do :D). Not sure how it works still.
I have link table called...
|
by: Charles Arthur |
last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
|
by: emmanuelkatto |
last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud.
Please let me know.
Thanks!
Emmanuel
|
by: BarryA |
last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
by: Hystou |
last post by:
There are some requirements for setting up RAID:
1. The motherboard and BIOS support RAID configuration.
2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
| |