Python split confusion

I am trying to alphabetically sort words from a file. However, the program sorts the lines, not the words, according to their first words. Here it is.

fname = raw_input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
    lst2 = line.strip()
    words = lst2.split()
    lst.append(words)
    lst.sort()
print lst

Here is my input file

But soft what light through yonder window breaks 
It is the east and Juliet is the sun 
Arise fair sun and kill the envious moon 
Who is already sick and pale with grief

And here is what I hope to get

['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', 'east', 'envious', 'fair', 'grief', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'the', 'through', 'what', 'window', 'with', 'yonder'] 
+4
source share
4 answers

The problem is what wordsis the array of your words from the split. When you add wordsin lst, you make a list of arrays, and sorting will only sort this list.

You want to do something like:

for x in words:
  lst.append(x)
lst.sort()

I believe

Edit: I have embedded your text file, this code works for me:

inp=open('test.txt','r')
lst=list()
for line in inp:
   tokens=line.split('\n')[0].split() #This is to split away new line characters but shouldnt impact
   for x in tokens:
     lst.append(x)
lst.sort()
lst
0
source

lst.append(words) lst, lst words. lst.extend(words) lst += words.

, , :

lst = []
for line in fh:
    lst2 = line.strip()
    words = lst2.split()
    lst.extend(words)
lst.sort()
print lst

, set:

st = set()
for line in fh:
    lst2 = line.strip()
    words = lst2.split()
    st.update(words)
lst = list(st)
lst.sort()
print lst
+7

lst.append(words) . :

lst = []
lst.append(['another','list'])
lst ## [['another','list']]

, . .extend(...):

fname = raw_input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
    lst2 = line.strip()
    words = lst2.split()
    lst.extend(words)
lst.sort()
print lst
+3

line.split() . , . lst.append(words), , . , extend(), .

, lst.append(words) lst.extend(words).

+2
source

Source: https://habr.com/ru/post/1613681/


All Articles