[Tutor] Finding word in file

Bernard Lebel 3dbernard at gmail.com
Wed May 18 16:33:49 CEST 2005


Hi Joseph,

To answer your last question first, you should use the
os.path.exsits() method to see if the path is valid:
http://www.python.org/doc/2.4.1/lib/module-os.path.html


As for finding a word in a text, I would suggest to write a basic text
parser that would work on small files.



def parseText():
	
	# oFile: text file to test
	# myWord: word we are looking for
	
	# Get all lines into list
	aLines = oFile.readlines()
	
	# Perform list comprehension on lines to test if the word is found
	for sLine in aLines:
		
		# Parse the line (remove spaces), returns list
		aLine = sLine.split()
		
		# Iterate words and test to see if they match our word
		for sWord in aLines:
			# if it matches, append it to our list
			if sWord == myWord: aWords.append( sWord )



# Create empty list to store all instances of the word that we may find
aWords = []

# Prompt user to know what word to search
myWord = str( raw_input( 'what word to searh:' ) )



Note that I'm still new to Python, there might be more efficient ways
to do that.

For larger text files (in the order of thousands of lines), you may
not use readlines() to build a list of the lines and insteand read one
line after another with readline() or xreadline() and append to the
list as you find the word.



Cheers
Bernard



On 5/18/05, Joseph Quigley <cpu.crazy at gmail.com> wrote:
> I'm making a program that opens a file and tries to find the word you specify.
> I can't get  it to find the word! I also would like to know how I can get
> it to print 2 lines above and 2 lines below the line with the word specified.
> One more thing, the try: IOError won't work... I type the name of a
> nonexistent file and the except won't kick in and print my error message!
> Not to mention the program is killed. How can i fix that?
> Thanks,
>          JQ
> 
> Full Code:
> 
> while True:
>      file_name = raw_input("Enter the full file name: ")
>      f = file(file_name, 'r')
>      try:
>          IOError
>      except:
>          print "File not found. Directories are not supported"
> 
>      while True:
>          line = f.readline()
>          if len(line) == 0:
>              break
>          find_word = raw_input("What word do you want to find (quit() to
> quit)?\n> ")
>          if find_word in file_name:
>              print f.readline(find_word)
>          elif find_word == "quit()":
>              break
>          print line,
>      f.close()
> 
>      close = raw_input("\n\nQuit program? (Y/N)> ")
>      if ((close == "Y") or ("y" == close)):
>          break
>      else:
>         print
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>


More information about the Tutor mailing list