python - 在 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
. 然后我需要将新完成的结果输出到一个新的文本文件中,文件中有数百行,我什至不知道从哪里开始。
解决方案
首先,您需要遍历数据,一次读取一行,然后重新格式化county, state
as 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 代码或使用大多数操作系统上的“排序”命令。
推荐阅读
- python - 如何迭代多个列表并仅在存在时打印出来
- java - 从数据库填充 jtree 时在 mysql 查询中使用 where
- javascript - 重构更简洁和高性能的代码
- xml - 选择中的 xsl 变量检查
- java - Dockerfile COPY failed: stat no such file, when using GitHub CI
- reactjs - 如何在 Redux 中管理嵌套的 reducer?
- c - 根据文件中的行创建数组
- uwp - 使用连续听写
- reactjs - 如何使用命令提示符检查当前版本的 React
- sql - sql中的nameUUIDFromBytes