Search for a word from a text file and count

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • frozz85
    New Member
    • Sep 2008
    • 4

    Search for a word from a text file and count

    I need to search through the file and look for lines that begin with "From". I need to parse the From line and print out the second word for each From line and then also count the number of From lines and print out a count at the end. I'm not sure what to do. Any help is appreciated.

    Code:
    import string
    fname = raw_input("Enter a file name: ")
    
    try:
       infile = open(fname, "r")
    except:
       print "File not found:", fname
       exit()
    
    x = 0
    for line in infile:
    
       words = string.split(line)
       print len(words), words
    
       if ( words[0] == 'From' ) :
          x = x + 1
          print x, words[1]
       elif (words[0] == ""):
          x = x
          continue
    print "There were",x,"lines in the file with From as the first word"
  • shreyask
    New Member
    • Sep 2008
    • 8

    #2
    Code:
    import string
    import sys
    
    if len(sys.argv) < 3:
        print "USAGE:", sys.argv[0], " <filename> <keyword>"
        sys.exit()
    else:
        filename = sys.argv[1]
        keyword = sys.argv[2]
    
    try:
        file = open(filename)
    except:
        print "File not found:", filename
        sys.exit()
    
    counter = 0
    
    for line in file.readlines():
        split_line = string.split(line)
    
        if len(split_line) > 0:
            if string.upper(split_line[0]) == string.upper(keyword):
                if len(split_line) > 1:
                    print split_line[1]
    
                counter = counter + 1
    
    print "total number of occurances of", keyword, "-", counter
    Last edited by shreyask; Sep 24 '08, 07:09 AM. Reason: bad formatting in original

    Comment

    • frozz85
      New Member
      • Sep 2008
      • 4

      #3
      Thank you so much!! :) I'm just a beginner, so I don't know the library sys yet. But it helps! Thank you!

      Originally posted by shreyask
      Code:
      import string
      import sys
      
      if len(sys.argv) < 3:
          print "USAGE:", sys.argv[0], " <filename> <keyword>"
          sys.exit()
      else:
          filename = sys.argv[1]
          keyword = sys.argv[2]
      
      try:
          file = open(filename)
      except:
          print "File not found:", filename
          sys.exit()
      
      counter = 0
      
      for line in file.readlines():
          split_line = string.split(line)
      
          if len(split_line) > 0:
              if string.upper(split_line[0]) == string.upper(keyword):
                  if len(split_line) > 1:
                      print split_line[1]
      
                  counter = counter + 1
      
      print "total number of occurances of", keyword, "-", counter

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        There is no need to use the string module. Following is an example using a file on my system.
        [code=Python]>>> f = open(r'D:\SDS2_ 7.1C\jobs\620_C aldwell\macro\6 20_Caldwell_Gri ds.txt', 'r')
        >>> output = []
        >>> for line in f:
        ... if line.lower().st artswith('recal l'):
        ... output.append(l ine)
        ...
        >>> f.close()
        >>> print 'The keyword occurred %d times.' % len(output)
        The keyword occurred 9 times.
        >>> print 'Words following the keywords: \n%s' % '\n'.join([w.strip().split ()[1] for w in output])
        Words following the keywords:
        20
        17
        21
        X
        Q
        S
        Z
        21
        3
        >>> [/code]

        Comment

        Working...