473,398 Members | 2,335 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,398 software developers and data experts.

How to loop through previous lines

22
Hi everyone. I have a text file looking like this:

Book ID: 1
Availability: on shelf > 3 borrows > 2
Name: Bread and Wine
Writer: Silone

Book ID: 2
Availability: on shelf > 4 borrows > 1
Name: Fontamara
Writer: Silone

Book ID: 3
Availability: on shelf > 3 borrows > 2
Name: Poirot
Writer: Agatha Christie

Book ID: 4
Availability: on shelf > 2 borrows > 2
Name: Miss Marple
Writer: Agatha Christie

and so on. I want to count the number of books by each writer and the total amount of their books been borrowed so far, to have a list like this:
-------------
Siolne 2 3
A. Christie 2 4
---------------

I have no idea how to go through this kind of blocks and specially grab a previous line from the block. Any help is appreciated.
Oct 14 '10 #1

✓ answered by Atrisa

Now it is working.

Expand|Select|Wrap|Line Numbers
  1. dd = {}
  2. for line in open('test.txt'):
  3.     if line.startswith('Writer'):
  4.         writer = line.split(':')[1].strip('\n')
  5.         dd.setdefault(writer, 0)
  6.         dd[writer] += 1
  7. print dd
  8.  

7 2210
bvdet
2,851 Expert Mod 2GB
Initialize a dictionary dd = {}
Loop through each line of text
If the line starts with "Writer", split the line on the colon character, add the writer to the dictionary as a key with a quantity of one.
If the writer is already in the dictionary, increment the value by one
OR the writer could be added this way:
Expand|Select|Wrap|Line Numbers
  1.     v = dd.get('Agatha Christie', 0)
  2.     dd['Agatha Christie'] = v+1
Oct 14 '10 #2
Atrisa
22
This is what I did, but don't know why it doesn't print anything:

Expand|Select|Wrap|Line Numbers
  1. f = open('test.txt').read()
  2.  
  3. dd = {}
  4. for line in f.split('\n\n'):
  5.     if line.startswith('Writer'):
  6.         writer = line.split(':')[0]
  7.         dd.get(writer, 0)
  8.         dd[writer] += 1
  9. print dd
  10.  
Oct 14 '10 #3
bvdet
2,851 Expert Mod 2GB
The way you did it, use dd.setdefault() instead of dd.get(). If you want the author's name, use index [1] instead of [0].
Oct 14 '10 #4
Atrisa
22
Still the dictionary is empty.
Oct 14 '10 #5
Atrisa
22
Now it is working.

Expand|Select|Wrap|Line Numbers
  1. dd = {}
  2. for line in open('test.txt'):
  3.     if line.startswith('Writer'):
  4.         writer = line.split(':')[1].strip('\n')
  5.         dd.setdefault(writer, 0)
  6.         dd[writer] += 1
  7. print dd
  8.  
Oct 14 '10 #6
bvdet
2,851 Expert Mod 2GB
Good job Atrisa!

BV
Oct 14 '10 #7
Atrisa
22
Thanks BV for your hints, helps and instructions:)
Oct 15 '10 #8

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

Similar topics

6
by: Larry Doan | last post by:
In a shell script or Perl, how do I open a file, find what I'm looking then Case 1: grab that line + the next 2 lines Case 2: grab that line + the previous 2 lines? TIA, Larry
15
by: Mike Lansdaal | last post by:
I came across a reference on a web site (http://www.personalmicrocosms.com/html/dotnettips.html#richtextbox_lines ) that said to speed up access to a rich text box's lines that you needed to use a...
21
by: JoKur | last post by:
Hello, First let me tell you that I'm very new to C# and learning as I go. I'm trying to write a client application to communicate with a server (that I didn't write). Each message from the...
2
by: Alan Silver | last post by:
Hello, I have code like the following... foreach (Control ctl in Page.Controls) { if (ctl.ID.StartsWith("X_")) { // do stuff } }
1
by: DAnne | last post by:
Hi, I have checked your archives but have not been able to find anything that works for my situation. I have a for loop that brings back a list of unique responses for each section in a report....
2
by: perltcl | last post by:
hi I've started learning python. I was typing from a tutorial, and I fail to indent on an inner loop. I got an error and all my previous typed lines are gone. is there a way to prevent this. i...
1
by: emlj001 | last post by:
I have a form that starts at page, http://www.scmeachoraldiv.org/allstate/registration/default.asp My problem is on the page http://www.scmeachoraldiv.org/allstate/registration/part2.asp I...
1
by: Doug_J_W | last post by:
I have a Visual Basic (2005) project that contains around twenty embedded text files as resources. The text files contain two columns of real numbers that are separated by tab deliminator, and are...
23
by: tshad | last post by:
Is there a way to know if you are looking at the last record record of foreach loop other then setting up a loop counter that you manually increment? foreach (Racecar racecar in...
2
by: dannywebster | last post by:
Hello all, I have a dictionary of which i'm itervalues'ing through, and i'll be performing some logic on a particular iteration when a condition is met with trusty .startswith('foo'). I need to...
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: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
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
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

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.