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

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • DjPal
    New Member
    • Dec 2009
    • 15

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

    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.

    -->
    Code:
    #!/usr/local/bin/python
    file = open("C:/Users/xyzl/Desktop/fruit.txt","r") #Open File.
    def appleno(fruit):
        res = 0
        
        for (apple) in auth:
            res = res+1
        return res
    -->
    thank you
    Last edited by bvdet; Feb 28 '10, 12:37 AM. Reason: Add code tags
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

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

    It would work like this:
    Code:
    f = open(file_name)
    total = 0
    for line in f:
        if "apple" in line:
            total += 1
    f.close()
    print total

    Comment

    • RashidSalmanov
      New Member
      • Jan 2017
      • 1

      #3
      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

      Comment

      Working...