0
votes

I'm a newbie in Python, and I need to write a code in Python that will read a text file, then split each words in it, sort it and print it out.

Here is the code I wrote:

fname = raw_input("Enter file name: ")
fh = open(fname)
lst = list()
words = list()


for line in fh:    

    line = line.strip()
    line.split()   
    lst.append(line)

lst.sort()
print lst

That's my output -

['Arise fair sun and kill the envious moon', 'But soft what light through yonder window breaks', 'It is the east and Juliet is the sun', 'Who is already sick and pale with grienter code herew', 'with', 'yonder']

However, when I try to split lst.split() it saying

List object has no attribute split

Please help!

3

3 Answers

2
votes

You should extend the new list with the splitted line, rather than attempt to split the strings after appending:

for line in fh:    
    line = line.strip()
    lst.extend(line.split())
0
votes

The issue is split() does not magically mutate the string that is split into a list. You have to do sth with the return value.

for line in fh:    
    # line.split()  # expression has has no effect
    line = line.split()  # statement does
    # lst += line  # shortcut for loop underneath
    for token in line:
        lst = lst + [token]
        lst += [token]

The above is a solution that uses a nested loop and avoids append and extend. The whole line by line splitting and sorting can be done very concisely, however, with a nested generator expression:

print sorted(word for line in fh for word in line.strip().split())
0
votes

You can do:

fname = raw_input("Enter file name: ")
fh = open(fname, "r")
lines = list()
words = list()
for line in fh:    
    # get an array of words for this line
    words = line.split()
    for w in words: 
       lines.append(w)

lines.sort()
print lines

To avoid dups:

no_dups_list = list()
for w in lines:
   if w not in no_dups_list:
       no_dups_list.append(w)