473,382 Members | 1,225 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,382 software developers and data experts.

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.

Expand|Select|Wrap|Line Numbers
  1. import string
  2. fname = raw_input("Enter a file name: ")
  3.  
  4. try:
  5.    infile = open(fname, "r")
  6. except:
  7.    print "File not found:", fname
  8.    exit()
  9.  
  10. x = 0
  11. for line in infile:
  12.  
  13.    words = string.split(line)
  14.    print len(words), words
  15.  
  16.    if ( words[0] == 'From' ) :
  17.       x = x + 1
  18.       print x, words[1]
  19.    elif (words[0] == ""):
  20.       x = x
  21.       continue
  22. print "There were",x,"lines in the file with From as the first word"
Sep 24 '08 #1
3 20417
Expand|Select|Wrap|Line Numbers
  1. import string
  2. import sys
  3.  
  4. if len(sys.argv) < 3:
  5.     print "USAGE:", sys.argv[0], " <filename> <keyword>"
  6.     sys.exit()
  7. else:
  8.     filename = sys.argv[1]
  9.     keyword = sys.argv[2]
  10.  
  11. try:
  12.     file = open(filename)
  13. except:
  14.     print "File not found:", filename
  15.     sys.exit()
  16.  
  17. counter = 0
  18.  
  19. for line in file.readlines():
  20.     split_line = string.split(line)
  21.  
  22.     if len(split_line) > 0:
  23.         if string.upper(split_line[0]) == string.upper(keyword):
  24.             if len(split_line) > 1:
  25.                 print split_line[1]
  26.  
  27.             counter = counter + 1
  28.  
  29. print "total number of occurances of", keyword, "-", counter
  30.  
Sep 24 '08 #2
Thank you so much!! :) I'm just a beginner, so I don't know the library sys yet. But it helps! Thank you!

Expand|Select|Wrap|Line Numbers
  1. import string
  2. import sys
  3.  
  4. if len(sys.argv) < 3:
  5.     print "USAGE:", sys.argv[0], " <filename> <keyword>"
  6.     sys.exit()
  7. else:
  8.     filename = sys.argv[1]
  9.     keyword = sys.argv[2]
  10.  
  11. try:
  12.     file = open(filename)
  13. except:
  14.     print "File not found:", filename
  15.     sys.exit()
  16.  
  17. counter = 0
  18.  
  19. for line in file.readlines():
  20.     split_line = string.split(line)
  21.  
  22.     if len(split_line) > 0:
  23.         if string.upper(split_line[0]) == string.upper(keyword):
  24.             if len(split_line) > 1:
  25.                 print split_line[1]
  26.  
  27.             counter = counter + 1
  28.  
  29. print "total number of occurances of", keyword, "-", counter
  30.  
Sep 24 '08 #3
bvdet
2,851 Expert Mod 2GB
There is no need to use the string module. Following is an example using a file on my system.
Expand|Select|Wrap|Line Numbers
  1. >>> f = open(r'D:\SDS2_7.1C\jobs\620_Caldwell\macro\620_Caldwell_Grids.txt', 'r')
  2. >>> output = []
  3. >>> for line in f:
  4. ...     if line.lower().startswith('recall'):
  5. ...         output.append(line)
  6. ...         
  7. >>> f.close()
  8. >>> print 'The keyword occurred %d times.' % len(output)
  9. The keyword occurred 9 times.
  10. >>> print 'Words following the keywords: \n%s' % '\n'.join([w.strip().split()[1] for w in output])
  11. Words following the keywords: 
  12. 20
  13. 17
  14. 21
  15. X
  16. Q
  17. S
  18. Z
  19. 21
  20. 3
  21. >>> 
Sep 24 '08 #4

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

Similar topics

10
by: Anand Pillai | last post by:
To search a word in a group of words, say a paragraph or a web page, would a string search or a regexp search be faster? The string search would of course be, if str.find(substr) != -1:...
5
by: jester.dev | last post by:
Hello, I'm learning Python from Python Bible, and having some problems with this code below. When I run it, I get nothing. It should open the file poem.txt (which exists in the current...
0
by: JF Potvin | last post by:
Hi ! I'm new to Perl and this group so any help is welcome. I've look around the groups a lot but I can't seems to find what I need. I have to do a script that connects to a specific web page...
83
by: D. Dante Lorenso | last post by:
Trying to use the 'search' in the docs section of PostgreSQL.org is extremely SLOW. Considering this is a website for a database and databases are supposed to be good for indexing content, I'd...
4
by: sun6 | last post by:
this is a program counting words from "text_in.txt" file and writing them in "text_out.txt". it uses binary tree search, but there is an error when i use insert () thanks for any help ...
5
by: STeve | last post by:
Hey guys, I currently have a 100 page word document filled with various "articles". These articles are delimited by the Style of the text (IE. Heading 1 for the various titles) These articles...
4
by: etuncer | last post by:
Hello All, I have Access 2003, and am trying to build a database for my small company. I want to be able to create a word document based on the data entered through a form. the real question is...
2
by: beanie | last post by:
i am a beginer in c programming and i am trying to Create a Concordance of Word Count for a Text File but my code is not working.pls can anyone helpme out.here is my code: #include <stdio.h>...
0
by: alivip | last post by:
I write code to get most frequent words in the file I won't to implement bigram probability by modifying the code to do the following: How can I get every Token (word) and ...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.