439,931 Members | 1,976 Online
Need help? Post your question and get tips & solutions from a community of 439,931 IT Pros & Developers. It's quick & easy.

# How to loop through previous lines

 P: 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

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 Replies

 Expert Mod 2.5K+ P: 2,851 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     v = dd.get('Agatha Christie', 0)     dd['Agatha Christie'] = v+1 Oct 14 '10 #2

 P: 22 This is what I did, but don't know why it doesn't print anything: Expand|Select|Wrap|Line Numbers f = open('test.txt').read()   dd = {} for line in f.split('\n\n'):     if line.startswith('Writer'):         writer = line.split(':')[0]         dd.get(writer, 0)         dd[writer] += 1 print dd   Oct 14 '10 #3

 Expert Mod 2.5K+ P: 2,851 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

 P: 22 Still the dictionary is empty. Oct 14 '10 #5

 P: 22 Now it is working. Expand|Select|Wrap|Line Numbers dd = {} for line in open('test.txt'):     if line.startswith('Writer'):         writer = line.split(':')[1].strip('\n')         dd.setdefault(writer, 0)         dd[writer] += 1 print dd   Oct 14 '10 #6

 Expert Mod 2.5K+ P: 2,851 Good job Atrisa! BV Oct 14 '10 #7

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