PythonExtract值在特定字符之后,并将其存储在列中

2024-09-29 21:35:54 发布

您现在位置:Python中文网/ 问答频道 /正文

文件输出.txt

    First name: Petar

    Last Name: Petrovic

    Age: 32

    Country: USA        
    This is some description

    First name: Nick

    Last Name: Cave

    Age: 22

    Country: Brasil      
   This is another description

如何使用python脚本获得以下输出:

 Petar Petrovic 32 USA
 Nick Cave 22 Brasil

到目前为止,我有这个

#!/bin/python
import sys
import os
import re   
with open ("output.txt", "r") as myfile:
data=myfile.read()

我读到我可能会使用字典,但不知道如何实现这一点


Tags: nameimporttxtageisdescriptionthiscountry
2条回答

@Aran Fey肯定有一个更简单的答案,但既然我已经写好了,还有另一个选择:

with open ("output.txt", "r") as myfile:
    output = []
    for line in myfile:
        if ":" in line:
            output.append(line.split(":")[1].strip())

to_print = []
for index, elem in enumerate(output):
    if ((index+1)%5 == 0):
        print(" ".join(to_print))
        to_print = []
    to_print.append(elem)

print(" ".join(to_print))

您可以使用正则表达式:

import re

people = re.findall(r'\bFirst name: (\S+)\s+Last Name: (\S+)\s+Age: (\d+)\s+Country: (\S+)', data)
for personinfo in people:
    print(' '.join(personinfo))

输出:

Petar Petrovic 32 USA
Nick Cave 22 Brasil

相关问题 更多 >

    热门问题