Python:组织文本文件

Python:组织文本文件,python,file,text,Python,File,Text,我制作了一个本地文本文件,看起来像这样: Houston 69.7 degrees F Brazosport 69.8 degrees F Miami 77.3 degrees F Carol City 77.3 degrees F North Westside 77.3 degrees F Hialeah 77.9 degrees F 我的任务是按字母顺序排列 这是我的尝试。不过,我似乎没法得到它。我的列表包含以字母表中每个字母开头的城市 for

我制作了一个本地文本文件,看起来像这样:

   Houston 69.7 degrees F

   Brazosport 69.8 degrees F

   Miami 77.3 degrees F

   Carol City 77.3 degrees F

   North Westside 77.3 degrees F

   Hialeah 77.9 degrees F
我的任务是按字母顺序排列

这是我的尝试。不过,我似乎没法得到它。我的列表包含以字母表中每个字母开头的城市

for aline in mf2:
        f = ord('A') + x
        g = ord(aline[2])
        if g == f:
            mf3.write(aline)
            x = x + 1
mf3.close()

如果文件足够小,则可以创建一个列表,将每行作为一个元素。 在这里,我过滤掉了空行,并从每行中去掉了空格(左端和右端)。可以使用lstrip()或rstrip()仅从左端或右端剥离。 test.txt完全包含您在上面给出的条目

def main():
    with open("test.txt") as infile, open("output.txt", "w") as outfile:
        lines = [line.strip(" ") for line in infile if line != "\n"]
        lines.sort()
        for line in lines:
            outfile.write(line)

if __name__ == '__main__':
    main()
应该是:

for aline in sorted(mf2):
    mf3.write(aline)
mf3.close()

令人震惊的是,Python没有现成的排序树。为什么不仅仅是
sorted()
函数呢?:它不是一个列表,所以我不能使用这个排序函数……但我能把它变成一个列表吗?这很有效!现在我必须根据温度值对列表进行排序。有什么想法吗?你明白了,哈哈。我刚刚算出了温度的问题,但别作弊。你只会伤害到自己。请用明确的文字解释代码,以便更具教育性。@LaszloPapp我用一些注释更新了答案
f = open("file.txt", "r")# read the input text file  
# omit empty lines and lines containing only whitespace
lines = [line for line in f if line.strip()] # frame list with each line as element
f.close() # close the opened file as we are already read lines from file
lines.sort() # sorting the lines from list
output = open("output.txt", "w")
for line in lines:
    output.write(line) # writing sorted lines to output file
output.close()