0

Problem: Open the file week.txt and read it line by line. For each line, split the line into a list of words using the split() function. The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append it to the list. When the program completes, sort and print the resulting words in alphabetical order. You can download the sample data at http://www.pythonlearn.com/code/romeo.txt

The file of week4.txt is the one I download from the website (remeo.txt) and name as week4.txt

fh = open(fname)
wordlist = []
x = 0
for line in fh:
    line = line.rstrip()
    words = line.split()
    wordsnum = len(words)
    while x < wordsnum:
        if x-1<1:
            firstword = words[x]
            wordlist = wordlist.append(firstword)
            x = x+1
            continue
        newword = words[x];
        if newword == words[x-1]:continue
        wordlist = wordlist.append(newword)
        x = x+1
wordlist = wordlist.sort()
print wordlist

enter image description here

I am having a problem with the append statement. Could you help me with this problem? Thank you very much!

Itteh Kitteh
  • 437
  • 5
  • 6
Max
  • 49
  • 1
  • 8
  • could you post the error in your post rather than a screenshot? thanks – Clay Jan 01 '16 at 03:37
  • It would be very appreciated if there are more constructive suggestions regarding to the solutions. Thanks – Max Jan 01 '16 at 03:51
  • 1
    Possible duplicate of [Python: Attribute Error - 'NoneType' object has no attribute 'something'](http://stackoverflow.com/questions/8949252/python-attribute-error-nonetype-object-has-no-attribute-something) – Clay Jan 01 '16 at 03:53

1 Answers1

0

The problem with my code is that I use

wordlist = wordlist.append(newword)

The fact is that append is a function, I cannot use the equal sign.

Therefore, the correct code should be

fname = raw_input('Enter file name: ')
if len(fname) == 0:
    fname = 'week4.txt'

fh = open(fname)
lst = list()
x = 0
for line in fh:
    words = line.strip().split()
    wordsnum = len(words)
    while x < wordsnum:
        if x-1<1:
            lst.append(words[x])
            x = x+1
            continue
        if words[x] == words[x-1]:continue
        lst.append(words[x])
        x = x+1
lst.sort()
print lst
Max
  • 49
  • 1
  • 8