473,396 Members | 2,109 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

How to group data read from a file?

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
Feb 12 '11 #1

✓ answered by bvdet

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.
Feb 12 '11 #2
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:
Expand|Select|Wrap|Line Numbers
  1. def main():
  2.  
  3.     new_rows = {}
  4.     values = []
  5.  
  6.     f=open('test.txt')
  7.     for line in f:
  8.  
  9.         values.append(line.rstrip('\n')[-1])
  10.  
  11.  
  12.         x = []         
  13.         x += values    
  14.  
  15.         for count in xrange(len(values)/4):
  16.             temp_values = (x.pop(3))+(x.pop(2))+(x.pop(1))+(x.pop(0))
  17.             new_rows['ROW'+str(count+1)] = temp_values
  18.         print new_rows        
  19.  
  20. if __name__ == '__main__':
  21.     main()
  22.  
Feb 13 '11 #3
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
Feb 13 '11 #4
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.
Expand|Select|Wrap|Line Numbers
  1. def main():
  2.     new_rows = []
  3.     values = []
  4.     f=open('test.txt')
  5.     f.next()
  6.     for line in f:
  7.         values.append(line.rstrip('\n')[-1])
  8.     f.close()
  9.     for count in xrange(0, len(values), 4):
  10.         new_rows.append(('ROW'+str((count/4)+1),values[count:count+4]))
  11.     print "\n".join(["%s=%s" % (item[0], "".join(item[1])) for item in new_rows])
  12.  
  13.  
  14. if __name__ == '__main__':
  15.     main()
Here's the way I was suggesting:
Expand|Select|Wrap|Line Numbers
  1. f = open("test.txt")
  2. f.next()
  3. dataList = []
  4. strList = []
  5. for i, line in enumerate(f):
  6.     strList.append(line.strip().split()[1])
  7.     if not (i+1)%4:
  8.         dataList.append("".join(strList))
  9.         strList = []
  10. f.close()
  11. output = "\n".join(["ROW%s=%s" % (i+1, dataList[i]) for i in range(len(dataList))])
  12. print output
Feb 13 '11 #5
bvdet
2,851 Expert Mod 2GB
For a Python editor, I prefer Pythonwin over Idle. There are several other good editors out there.
Feb 13 '11 #6
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:
Expand|Select|Wrap|Line Numbers
  1. f = open("test2.txt") 
  2. f.next() 
  3. dataList = [] 
  4. strList = [] 
  5. for i, line in enumerate(f): 
  6.     strList.append(line.strip().split()[-1]) 
  7.     if not (i+1)%128: 
  8.         dataList.append("".join(strList)) 
  9.         strList = [] 
  10. f.close() 
  11. output = "\n".join(["ROW%s=%s" % (i+1, dataList[i]) for i in range(len(dataList))]) 
  12. print output 
  13.  
and it seems to be working too. :)
Attached Files
File Type: txt test2.txt (15.6 KB, 396 views)
Feb 13 '11 #7
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().
Feb 14 '11 #8
i notice the code extracts until 128x4=512. there are 8 characters being truncated. total there are 520. how do i resolve this? tq
Feb 14 '11 #9
bvdet
2,851 Expert Mod 2GB
strList will contain data. Test for this condition and add to output as needed.
Feb 14 '11 #10
thanks for your advice. :)
Feb 14 '11 #11

Sign in to post your reply or Sign up for a free account.

Similar topics

0
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...
3
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...
3
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.
5
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...
3
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
2
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...
4
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...
1
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...
2
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...
5
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
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
0
BarryA
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...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
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...
0
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...
0
jinu1996
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...
0
tracyyun
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...
0
agi2029
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,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.