簡體   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