[英]Extract each element of each list after the reading a file, Using Python
I think the other time I asked my question incorrectly enter link description here 我想我有一次不正确地问了问题, 在这里输入链接描述
I have a file .txt, like this: 我有一个.txt文件,如下所示:
.
.
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.
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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.