简体   繁体   English

带有 Python 的 Separating.txt 文件

[英]Separating .txt file with Python

I have to separate.txt file into small pieces, based on the matched value.我必须根据匹配值将 .txt 文件分成小块。 For example, I have.txt file looks like:例如,我有 .txt 文件如下所示:

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

I have to extract all rows with the same value “Age” and to copy them to other file or perfom some other action..我必须提取具有相同值“Age”的所有行并将它们复制到其他文件或执行其他操作..

How it is possible to be done with Python, I have never do that before.如何使用 Python 完成,我以前从未这样做过。

Thank you in advance:)先感谢您:)

I am asking, because of I have no idea how it should be done.我在问,因为我不知道应该怎么做。 The excpected result is to have this data separated:预期的结果是将这些数据分开:

Names Age Country
Mark 19 USA
John 19 UK

Names Age Country
Elon 20 CAN

Names Age Country
Dominic 21 USA
Andreas 21 UK

Here is a possible solution:这是一个可能的解决方案:

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

For the sample you posted, the code above will leave you with files named age-19.txt , age-20.txt , and age-21.txt , with the contents separated by age, as you requested.对于您发布的示例,上面的代码将为您留下名为age-19.txtage-20.txtage-21.txt ,内容按照您的要求以年龄分隔。

If you have them all in a list you can use something like this...如果你把它们都放在一个列表中,你可以使用这样的东西......

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)

Will print two different lists of your separated players.将打印两个不同的分离玩家列表。

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

['Names Age Country', 'Mark 21 USA', 'John 21 UK', 'Dominic 21 USA', 'Andreas 21 UK'] ['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