繁体   English   中英

带有 Python 的 Separating.txt 文件

[英]Separating .txt file with Python

我必须根据匹配值将 .txt 文件分成小块。 例如,我有 .txt 文件如下所示:

Names Age Country
Mark 19 USA
John 19 UK
Elon 20 CAN
Dominic 21 USA
Andreas 21 UK

我必须提取具有相同值“Age”的所有行并将它们复制到其他文件或执行其他操作..

如何使用 Python 完成,我以前从未这样做过。

先感谢您:)

我在问,因为我不知道应该怎么做。 预期的结果是将这些数据分开:

Names Age Country
Mark 19 USA
John 19 UK

Names Age Country
Elon 20 CAN

Names Age Country
Dominic 21 USA
Andreas 21 UK

这是一个可能的解决方案:

with open('yourfile.txt') as infile:
    header = next(infile)
    ages = {}

    for line in infile:
        name, age, country = line.rsplit(' ', 2)
        if age not in ages:
            ages[age] = []
        ages[age].append([name, age, country])

    for age in ages:
        with open(f'age-{age}.txt', 'w') as agefile:
             agefile.writeline(header)  
             agefile.writelines(ages[age])

对于您发布的示例,上面的代码将为您留下名为age-19.txtage-20.txtage-21.txt ,内容按照您的要求以年龄分隔。

如果你把它们都放在一个列表中,你可以使用这样的东西......

alltext = ["Names Age Country", "Mark 21 USA", "John 21 UK","Elon 20 CAN","Dominic 21 USA", "Andreas 21 UK"]

Canada = [alltext[0]] #Creates a list with your column header
NotCanada = [alltext[0]] #Creates a list with your column header

for row in alltext[1:]:
    x = row.split()
    if x[2] == "CAN":
        Canada.append(row)
    else:
        NotCanada.append(row)

print(Canada)
print(NotCanada)

将打印两个不同的分离玩家列表。

['命名年龄国家','Elon 20 CAN']

['Names Age Country', 'Mark 21 USA', 'John 21 UK', 'Dominic 21 USA', 'Andreas 21 UK']

暂无
暂无

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

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