【问题标题】:How to read the line that contains a string then extract this line without this string如何读取包含字符串的行,然后在没有该字符串的情况下提取该行
【发布时间】:2018-05-26 07:35:00
【问题描述】:

我有一个包含特定行的文件 .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.

【问题讨论】:

  • 所以你问如何删除字符串的前 4 个字符?以及如何用逗号分割字符串?
  • 在分割部分你需要打印 o_T 而不是 o_t。
  • 我正在尝试消除前两个。
  • 是的,你是对的,我会更正

标签: python python-3.x


【解决方案1】:

使用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_Fname = M.A. o_Ltname = Wood 中的“o_A”分开
【解决方案2】:

您的问题是打印 o_t 而不是 o_T (这是拆分操作的结果)。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多