在读取文件之后,使用Python提取每个列表的每个元素

2024-05-19 01:05:36 发布

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

我想上次我问错问题了enter link description here

我有一个.txt文件,如下所示:

.
.
T - Python and Matplotlib Essentials for Scientists and Engineers
.
A - Wood, M.A.
.
.
.

我想提取行中的一部分并提取每个列表的每个元素,以下是我的脚本:

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)

以及我想要的输出:

Python and Matplotlib Essentials for Scientists and Engineers
Wood 
M.A.

Tags: andintxtnoneformatplotliblinefilter
1条回答
网友
1楼 · 发布于 2024-05-19 01:05:36

我键入如下脚本:

#!/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()

输出:

Python and Matplotlib Essentials for Scientists and Engineers
Wood
M.A.

相关问题 更多 >

    热门问题