首页 > 解决方案 > 在 Python 中对文本列进行排序

问题描述

我是一个非常新手的编码器,需要帮助组合和重新排列大量 .txt 数据。该文件目前列出如下:

A

lcorn, MS
Aleutians East, AK
Aleutians West, AK
Alexander, IL
Alexander, NC
Alexandria, VA
Alfalfa, OK
Alger, MI
Allamakee, IA
Allegan, MI
Allegany, MD
Allegany, NY
Alleghany, NC
Alleghany, VA
Allegheny, PA
Allen, IN
Allen, KS
Allen, KY
Allen, LA
Allen, OH
Allendale, SC
Alpena, MI
Alpine, CA
Amador, CA
Amelia, VA
Amherst, VA
Amite, MS

我需要重新排列数据,使其看起来像

MS: Alcorn
AK: Aleutians East
AK: Aleutians West

基本上格式为(State): County. 然后我需要将新完成的结果输出到一个新的文本文件中,文件中有数百行,我什至不知道从哪里开始。

标签: pythontext-files

解决方案


首先,您需要遍历数据,一次读取一行,然后重新格式化county, stateas state: county

尝试:

with open('data.txt', "r") as fin, open('out.dat', "w") as fout:
    line = fin.readline()    
    while line:
        pos = line.rfind(',')
        if pos > 1:
            # input: Aleutians West, AK
            # reformat AK: Aleutians West
            line = "{}: {}".format(line[pos+1:].strip(), line[0:pos])
            fout.write(line)
        elif line.strip() != '':
            # otherwise no comma so not in county, state form
            print("skip:", line)
        line = fin.readline()

输出:

MS: Alcorn
AK: Aleutians East
AK: Aleutians West
IL: Alexander
NC: Alexander
...

县名中可能会出现逗号 (,),因此上面的代码line.rfind(',')用于查找行中的最后一个 ','。如果没有行中有多个逗号,那么您可以安全地使用它line.find(',')来查找第一个逗号。

接下来,如果您想按州和县对输出文件进行排序,那么您可以使用 Python 代码或使用大多数操作系统上的“排序”命令。


推荐阅读