[Tutor] Looking for Words - Help

Mark Lawrence breamoreboy at yahoo.co.uk
Sat Oct 12 10:15:37 CEST 2013


On 12/10/2013 06:18, Jackie Canales wrote:
> from string import punctuation
> #helper function

I'd be inclined to call this strippunc as strip is use so often.

> def strip(text):
>      'returns text with all punctuation removed'
>
>      for symb in punctuation: #import from string
>          text = text.replace(symb, ' ')
>      return text

Just for reference instead of replace you might like to consider the 
string translate method and its associated maketrans see 
http://docs.python.org/3/library/stdtypes.html#str.translate and 
http://docs.python.org/3/library/stdtypes.html#str.maketrans.  They're 
in the string module in Python 2.

>
> #helper function
> def wordin(s,t):
>      'does word s occur in text t'
>      #s in t
>      t = strip(t)
>      return s in t.split()
>
> def lines(name, word):
>      'print all lines of name in which word occurs'
>
>      infile = open(name, 'r')
>      lst = infile.read()
>      infile.close()
>
>      for line in lst.splitlines():
>          if word in line:
>             words = line
>      for index, word in enumerate(words):
>          print(words)

I suspect you want print(word) above :)  Better yet print(index, word) 
will show you exactly what you're getting.  Also see further below.

>
> LINK TO CODE:http://codetidy.com/6926/
>
> Thank you for the help so far! I figured out how to split the file in
> order to only out all the lines that have the word river in it. I tried
> reading up on enumerate but I am still having trouble understanding it.
> The code above just repeats this line in the middle of the page about 20
> times.
>
>      probably essentially dam the widest river in the world.
> LINK: http://imgur.com/7pZvfzA
>
> I tried understanding the feedback given to me the above is what i got
> so far if you could please help me with the enumerate.
>

Enumerate simply pulls an item from some iterable such as a list with an 
associated index which has a default start number of zero.  The example 
from http://docs.python.org/3/library/functions.html#enumerate

 >>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
 >>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
 >>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

Note that the above is taken from an interactive session.  If you 
haven't used this extremely powerful tool please start doing so 
immediately, it's one of Python's most powerful features.  It may well 
help you to try this by actually typing in some of the code from Peter 
Otten's original reply to your post.

HTH.

-- 
Roses are red,
Violets are blue,
Most poems rhyme,
But this one doesn't.

Mark Lawrence



More information about the Tutor mailing list