[Tutor] Looking for Words - Help

Jackie Canales jackiexxduh at yahoo.com
Fri Oct 11 07:18:27 CEST 2013


Need assistance with a questions in regards to python:
1. function occurs(name, word) which looks for a word in the file with name name.
2. for each occurrence of the word we want to display its context by showing the 5 words (or so) preceding and following the occurrence, e.g. '... a man to set the river on fire. He had ...' for the first occurrence of 'river' in 'innocents.txt'.
3. since the results may be long, we want to collect them all, and write them to a file whose name should be 'occurs'+name.

Hint: at first ignore writing the results to a file. Simply collect all material in a string which you print to the screen. Then writing it to a file will be simple. To get both the word and its context you need an indexed loop through the words. Use the stripw() function we saw on individual words to make finding hits more accurate (e.g. the program found 'river.' above). Finally, the join() method will come in handy to reconstruct the context as a string.


Link to final product: http://imgur.com/q1aAAhp

For my program this is what i have so far, I am kinda lost at this point if you can please guide me to help resolve this program.

def lines(name, word):
    'print all lines of name in which word occurs'

    infile = open(name, 'r')
    lst = infile.readlines()
    infile.close()

    for i in range(len(lst)):
        line = lst[i]
        if wordin(word, line):
            w = ('Word found in line {}:'.format(i))
            #x = (lst[i+1])
            y = lst[i]        
             
            print (''.join(y))
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20131010/564c6f11/attachment.html>


More information about the Tutor mailing list