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

2024-05-19 01:04:46 发布

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

我有一个包含特定行的.txt文件,如下所示

文件.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,M.A.”),我还可以提取姓和名。 因此最终结果将是:

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

Tags: and文件字符串intxtformatplotlibline
2条回答

使用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(这是分割操作的结果)

然而,正如其他人指出的那样,您也可以通过删除前4个字符来实现这一点,通过使用regex \w - (.+),然后您可以获得所有的值。如果还需要第一个字符,可以使用(\w) - (.+)

除此之外,如果给变量起个更好的名字,你的生活也会更好:)

相关问题 更多 >

    热门问题