繁体   English   中英

如何读取包含字符串的行,然后提取不包含此字符串的行

[英]How to read the line that contains a string then extract this line without this string

我有一个包含特定行的.txt文件,像这样

file.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 = o_t.split('T - ')
print (o_T)

o_A = o_a.split('A - ')
#o_Fname =
#o_Lname =
print (o_A)

我的输出:

['', 'Python and Matplotlib Essentials for Scientists and Engineers']
['', 'Wood, M.A.']

和我想要的输出:

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

此外,对于第二个名称(“ Wood,MA”),我也可以提取姓氏和名字。 因此最终结果将是:

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

使用filter从列表中删除所有空元素。

例如:

o_T = filter(None, o_t.split('T - '))
print (o_T)
o_A = filter(None, o_a.split('A - '))
print (o_A)

输出:

['Python and Matplotlib Essentials for Scientists and Engineers']
['Wood, M.A.']

您的情况是,您打印o_t而不是o_T(这是拆分操作的结果)。

但是,正如其他人指出的那样,您也可以通过使用regex \\w - (.+)删除前4个字符来解决此问题,然后可以获得所有值。 如果还需要第一个字符,则可以使用(\\w) - (.+)

除此之外,如果给变量赋予更好的名称,您的生活也会更好:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM