python - 如何将文本文件转换为列表,然后使用 Python 对其进行排序?

标签 python list sorting python-2.x

我有一个包含以下歌词的文本文件:

'First verse Im off till I'm off the island
i'm riding like autoban on autopilot
before I touch dirt I deal you all with kindness
my natual persona much worse'

我想将其转换为列表,然后按字母顺序排序,但我不断得到的是:[[First', 'verse', 'Im', 'off', 'till, "I' m", 'off' , 'the', 'island'] [然后打印第三行], [然后第二行], [然后第四行]]

然后将其放入列表中的列表中[[ text, text..., ]]

如何打印它,以便它在一个列表中按顺序打印并排序 使用python代码按字母顺序排列?这是我到目前为止所拥有的:

fname = raw_input("Enter file name: ")  #prompts user for .txt file
fhand = open(fname)     #reads file
NewList =  []    #creating new list to append to
for line in fhand:    #for the lines in the text file, read them
    line.rstrip()   # strip the white space
    words = line.split()   #split the txt file into string words

    for word in words:      #for every word in txt file
        if words not in NewList:  #if not in the NewList
                NewList.append(words) #then appended words to Newlist 

                NewList.sort()    #sort it alphabetically

print NewList   #then print the sorted list

最佳答案

一行就可以实现!

sorted(open('file.txt').readlines())

或者,如果您希望将其像单个文件一样打印

print "".join(sorted(open('file.txt').readlines()))

关于python - 如何将文本文件转换为列表,然后使用 Python 对其进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29304835/

相关文章:

python - Numpy longdouble 算术似乎不在 long double with conversion

python - 使用 Tkinter 在消息框中显示进度

c# - Sorted 为真时 SelectedValue 的问题(ComboBox)

javascript - 如何对多个 Google 工作表中的特定列进行排序

c# - 更改 gridview 中超链接的 css 属性的问题

python - 将列级别由内而外

python - 自动关闭 kivy 中的弹出窗口

python - 堆叠 Pandas 数据框

python - 如何根据Python列表中出现在该元素之前的元素来访问该元素

Python,在列表列表中,将第一个列表的第一个元素与第二个列表的第一个元素进行比较