[Tutor] searching a file for a specific word

Benoit Dupire bdupire@seatech.fau.edu
Wed, 02 May 2001 10:10:01 -0400


The following function does something similar....
It looks for a word in a web page (it was post by Remco a few weeks ago)

You can transpose it to your problem
The open function returns a file object you can read from...
page is actually all the text in the file... (here the webpage)

 use string.find... it's a convenient function for your problem...:o)


def find_word(url, word):
    import urllib, string
    page = urllib.URLopener().open(url).read()
    if string.find(page, word) != -1:
       return 1
    else:
       return 0



Benoit (tks Remco.. :o) )

Vladimir.Denis@olsinc.net wrote:

> Hello everyone, this is my first attempt at programming and I have chosen
> python because I was told that it's easy to learn.  In any event I thought
> that for my first script I would write a program that would be able to find
> a word or words in a file.  The problem is I'm stuck.  Below you will find
> what I have done so far and any advice will be appreciated.  As you will
> note, I have figured out how to get the file name, the words to be searched
> for, but I don't know how to actually search for the words.  The only thing
> I could think of so far is to use the os module and use the grep command
> but I'm sure there's another way and I can't figure it out.  Since I'm new
> to programming I am not too familiar with strings (and I'm sure this is
> probably part of the solution).
>
> #/usr/bin/python
>
> # this script will print specific words from a file
> # (most likely a log file) to desktop
>
> import os, string, sys
>
> names = []
> logf = sys.argv[-1]
>
> ###############################################################
> ## opens the /var/log/messages file by default or other file ##
> ###############################################################
>
> if (logf[0:1] == "/"]
>      filename = logf
>      names.append(sys.argv[1:-1]
>      found = open("filename","r")
>
> else:
>      filename = "/var/log/messages"
>      names.append(sys.argv[1:-1]
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

--
Benoit Dupire
Graduate Student
----------------
I'd like to buy a new Boomerang. How can i get rid of the old one?