简体   繁体   English

对列表中文件的单词进行排序

[英]Sorting words of a file in a list

I am trying to sort all the words of a text file in alphabetical order.我正在尝试按字母顺序对文本文件的所有单词进行排序。 Here is my code:这是我的代码:

filename=input('Write the name of the file :')
fh=open(filename)
wlist=list()
for line in fh:
    line=line.rstrip()
    ls=line.split()
    for w in ls:
        if w not in wlist:
        wlist.append(w)            
print(wlist)

The output is ok but whenever I try print(wlist.sort()) it gives 'None' as output instead of sorting the wlist.what is the problem in my code? output 没问题,但是每当我尝试print(wlist.sort())时,它都会给出“无”为 output 而不是对 wlist 进行排序。我的代码有什么问题?

Thanks in advance.提前致谢。

list.sort sorts the list in-place and returns None . list.sort对列表进行就地排序并返回None
If you want to print the sorted list, do it afterwards:如果要打印排序列表,请稍后执行:

wlist.sort()
print(wlist)

Separately, instead of checking the list for duplicates every time it'd be far more efficient to make a set of the words, and then sort that with sorted() :另外,不是每次都检查列表中的重复项,而是创建一set单词,然后使用sorted()对其进行排序会更有效率:

words = set()
for line in file:
    for word in line.split():
        words.add(word)

print(sorted(words))

There were some indentation inconsistencies but other then that its good.有一些缩进不一致,但除此之外它很好。 As a general rule the function sort() only performs the ordering of items in the list.作为一般规则,function sort()仅执行列表中项目的排序。 If you want to return the list print it:如果要返回列表打印它:

filename=input('Write the name of the file :')

wlist = []
# I would recommend opening files in this format
with open(filename) as f_obj:
   read = f_obj.readlines()

for line in read:
    ls = line.split(' ')
    for w in ls:
        if w not in wlist:
            wlist.append(w)

wlist.sort()               
print(wlist)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM