我认为另一次我错误地提出了我的问题enter link description here
我有一个文件.txt,就像这样:
int main(){
int dp[3][3];
string A,B;
string array[] = {"axd","byd","axd"};
for (int i = 0 ; i < 3; i++){
A = array[i];
for (int j = 0; j<3; j++){
B = array [j];
if(A[i] == B[j]){
dp[i][j] =1;
cout << dp[i][j] << endl;
}else
dp[i][j] = 0;
}
}
for(int i = 0; i<3; i++){
for(int j = 0; j<3; j++){
//cout << dp[i][j];
}
//cout << endl;
}
return 0;
}
我想提取行中的一部分并提取每个列表的每个元素,这是我的脚本:
.
.
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 = filter(None, o_t.split('T - '))
list_o_T = [o_T]
o_Title = list_o_T[0]
print (o_Title)
o_A = filter(None, o_a.split('A - '))
list_o_A = [o_A]
o_Lname = list_o_A[0]
o_Fname = list_o_A[1]
print (o_Lname)
print (o_Fname)
答案 0 :(得分:1)
我按如下方式输入脚本:
#!/usr/bin/env python3.6
from pathlib import Path
def main():
for line in Path('file.txt').read_text().split('\n'):
if 'T - ' in line:
o_t = line.replace('T - ', '')
elif 'A - ' in line:
o_Lname, o_Fname = line.replace('A - ', '').split(', ')
print(o_t)
print(o_Lname)
print(o_Fname)
if __name__ == '__main__':
main()
输出:
Python and Matplotlib Essentials for Scientists and Engineers
Wood
M.A.