Reputation: 11
Hello everyone I have a file of which consist of some random information but I only want the part that is important to me.
name: Zack
age: 17
As Mixed: Zack:17
Subjects opted : 3
Subject #1: Arts
name: Mike
age: 15
As Mixed: Mike:15
Subjects opted : 3
Subject #1: Arts
Above is a example of my text file I want Zack:17 and Mike:15 part to be written in a text file and everything else to be ignored.
I watched some YouTube videos and came across split statement in python but it didn't work.
My code example
with open("/home/ninja/Desktop/raw.txt","r") as raw:
for rec in raw:
print rec.split('As Mixed: ')[0]
This didn’t work. Any help will really help me to finish this project. Thanks.
Upvotes: 1
Views: 2251
Reputation: 778
Try this
import re
found = []
match = re.compile('(Mike|Zack):(\w*)')
with open('/hope/ninja/Destop/raw.twt', "r") as raw:
for rec in raw:
found.extend(match.find_all(rec))
print(found)
#output: [('Mike', '15'), ('Zack', '17')]
This uses regular expressions to find the value needed, basically (Mike|Zack):(\w*)
finds Mike or Zack and then a :
character and then as many word as it can find.
To learn more about regular expressions you can read from this website: https://docs.python.org/3.4/library/re.html
Upvotes: 0
Reputation: 71451
You can split the data at the :
and grab only As Mixed
parameter
content = [i.strip('\n').split(': ') for i in open('filename.txt')]
results = [b for a, b in content if a.startswith('As Mixed')]
Output:
['Zack:17', 'Mike:15']
To write the results to a file:
with open('filename.txt', 'w') as f:
for i in results:
f.write(f'{i}\n')
Upvotes: 1