【发布时间】: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