Python:组织文本文件

时间:2014-02-22 03:41:51

标签: 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 aline in mf2:
        f = ord('A') + x
        g = ord(aline[2])
        if g == f:
            mf3.write(aline)
            x = x + 1
mf3.close()

3 个答案:

答案 0 :(得分:1)

如果您的文件足够小,您可以创建一个列表,其中每行都是一个元素。 在这里,我过滤掉了空行,并从每一行中去掉了空格(左端和右端)。您可以使用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()

答案 1 :(得分:1)

应该是:

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

答案 2 :(得分:0)

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()