424,303 Members | 1,356 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,303 IT Pros & Developers. It's quick & easy.

counting the occurrences of specific terms in a text file, in python

DjPal
P: 15
Say I have a text file containing entries, and I want to count the number of entries which have the word "apple" in them.

I have tried the following code, anyone knows what would help? learning python.

-->
Expand|Select|Wrap|Line Numbers
  1. #!/usr/local/bin/python
  2. file = open("C:/Users/xyzl/Desktop/fruit.txt","r") #Open File.
  3. def appleno(fruit):
  4.     res = 0
  5.  
  6.     for (apple) in auth:
  7.         res = res+1
  8.     return res
-->
thank you
Feb 28 '10 #1

✓ answered by bvdet

Please use code tags when posting code. See Posting Guidelines here.

It would work like this:
Expand|Select|Wrap|Line Numbers
  1. f = open(file_name)
  2. total = 0
  3. for line in f:
  4.     if "apple" in line:
  5.         total += 1
  6. f.close()
  7. print total

Share this Question
Share on Google+
2 Replies


bvdet
Expert Mod 2.5K+
P: 2,851
Please use code tags when posting code. See Posting Guidelines here.

It would work like this:
Expand|Select|Wrap|Line Numbers
  1. f = open(file_name)
  2. total = 0
  3. for line in f:
  4.     if "apple" in line:
  5.         total += 1
  6. f.close()
  7. print total
Feb 28 '10 #2

P: 1
But ur(bvdet) code consider the "apple" term as a unit in each string not depending on the amount. What can we do in order to make a code count all the apples in strings?
Thanks in advance
Jan 4 '17 #3

Post your reply

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