Reputation: 63
I think the other time I asked my question incorrectly enter link description here
I have a file .txt, like this:
.
.
T - Python and Matplotlib Essentials for Scientists and Engineers
.
A - Wood, M.A.
.
.
.
I would like to extract a part in the lines and extract each element of each list, here is my script:
with open('file.txt','r') as f:
for line in f:
if "T - " in line:
o_t = line.rstrip('\n')
elif "A - " in line:
o_a = line.rstrip('\n')
o_T = filter(None, o_t.split('T - '))
list_o_T = [o_T]
o_Title = list_o_T[0]
print (o_Title)
o_A = filter(None, o_a.split('A - '))
list_o_A = [o_A]
o_Lname = list_o_A[0]
o_Fname = list_o_A[1]
print (o_Lname)
print (o_Fname)
and my desired output:
Python and Matplotlib Essentials for Scientists and Engineers
Wood
M.A.
Upvotes: 0
Views: 72
Reputation: 6341
I type a script as follows:
#!/usr/bin/env python3.6
from pathlib import Path
def main():
for line in Path('file.txt').read_text().split('\n'):
if 'T - ' in line:
o_t = line.replace('T - ', '')
elif 'A - ' in line:
o_Lname, o_Fname = line.replace('A - ', '').split(', ')
print(o_t)
print(o_Lname)
print(o_Fname)
if __name__ == '__main__':
main()
Output:
Python and Matplotlib Essentials for Scientists and Engineers
Wood
M.A.
Upvotes: 1