我有一个包含以下歌词的文本文件:
'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/