file output.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()
我读到我可能会使用字典但不知道如何实现它。
答案 0 :(得分:3)
您可以使用正则表达式:
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
答案 1 :(得分:0)
@ 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))