Thanks, everyone, for your help.

The objective was to extract all words from each line and place them in a
list IF they didn't already exist in it.
I sorted it out by adding little bits of everyone's suggestions.

Here's the code that fixed it.

fname = raw_input('Enter file name:\n')
try:
    fhand = open(fname)
except:
    print 'File cannot be found or opened:', fname
    exit()
lst = list()
for line in fhand:
    words = line.split()
    for word in words:
        if word in lst:
            continue
        else:
            lst.append(word)
lst.sort()
print lst

I named the file WordExtract.py since it does just that. :)

*Warm regards,*

*Olaoluwa O. Thomas,*
*+2347068392705*

On Thu, Jun 2, 2016 at 6:44 PM, Steven D'Aprano <st...@pearwood.info> wrote:

> On Thu, Jun 02, 2016 at 06:05:43PM +0100, Olaoluwa Thomas wrote:
>
> > fname = raw_input('Enter file name:\n')
> > try:
> >     fhand = open(fname)
> > except:
> >     print 'File cannot be found or opened:', fname
> >     exit()
> > lst = list()
> > for line in fhand:
> >     words = line.split()
> >     #print words (this was a test that a portion of my code was working)
> >     lst.append(words)
>
> If you printed words, you should have seen that it was a list.
>
> If you append a list to a list, what do you get? At the interactive
> prompt, try it:
>
>
> py> L = [1, 2, 3]
> py> L.append([4, 5, 6])
> py> L
> [1, 2, 3, [4, 5, 6]]
>
>
> Append takes a single argument, and adds it *unchanged* to the end of
> the list.
>
> What you want is the extend method. It takes a list as argument, and
> appends each item individually:
>
>
> py> L.extend([7, 8, 9])
> py> L
> [1, 2, 3, [4, 5, 6], 7, 8, 9]
>
>
> But if you didn't know about that, you could have done it the
> old-fashioned way:
>
> lst = list()
> for line in fhand:
>     words = line.split()
>     for word in words:
>         lst.append(word)
>
>
>
> --
> Steve
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to