[英]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.