-2

I have a .txt file called test1.txt which contains:

apple
P apple apple
P apple
Pbanana apple P apple apple apple

I split it into catagories based on the letter P using this code:

import re

Apple_split = open("test1.txt").read().split("P")

print(Apple_split_split)

I now wish to count the number of times the word apple occurs within each split. Hopefully coming out with an output such as 1, 2, 1, 1, 3 or something like that. Any help would be appreciated.

  • 1
    Possible duplicate: http://stackoverflow.com/questions/1374457/find-out-how-many-times-a-regex-matches-in-a-string-in-python – ambi Jul 12 '14 at 23:02
  • note that you `import re` but are not using it in the code shown. – Stuart Jul 12 '14 at 23:05

2 Answers2

0

Use string.count within a list comprehension to apply it to each of the split segments.

with open('test1.txt') as text_file:
    print [segment.count('apple') for segment in text_file.read().split("P")]
Stuart
  • 9,597
  • 1
  • 21
  • 30
  • I tried this but its just gives me the total number of apples. Im trying to find the number of apples in each split. – user3797765 Jul 12 '14 at 23:11
  • The list comprehension does exactly what you want. Try it as it is written here; it returns [1, 2, 1, 1, 3]. http://repl.it/VSm – Stuart Jul 12 '14 at 23:21
0

You can do something like this:

f = open('test1.txt').read().split('P')
apple_counts = [segment.count('apple') for segment in f]
print apple_counts #[1, 2, 1, 1, 3]

The above uses a simple list comprehension after splitting each segment by the 'P'.

ZenOfPython
  • 891
  • 6
  • 15