我写了一个脚本来处理以'>'开头的生物识别文件,但现在我有相同的文本文件没有'>',我改变我的脚本,但它没有显示输出。 这是我的剧本
with open('input1.txt', 'rb') as file1:
file1_data = dict(line.split(None, 2)[1::-1] for line in file1 if line.strip())
with open('input2.txt', 'rb') as file2, open('output.txt', 'wb') as outputfile:
output = csv.writer(outputfile, delimiter='|')
for line in file2:
if line[:1] == '>':
row = line.strip().split('|')
key = row[0][1:]
if key in file1_data:
output.writerow(row + [file1_data[key]])
else:
outputfile.write(line)
这是input1:
Q5 Bat Wood
Q6 Ball Tough
Q7 Pitch Dry
这是输入2:
>Bat|Batsman
>Ball|Bowler
>Pitch|Cricket
所以程序将input1的第二行与input2的第一行匹配,如果匹配,则将input1的row1与input2相连,如output
:
>Bat|Batsman|Q5
>Ball|Bowler|Q6
>Pitch|Cricket|Q7
但Now
我的input2
文件更改为
输入2:
Bat|batsman 8
Ball|bowler 4
Pitch|matches 9
必需的输出
Bat|batsman|Q5 8
Ball|bowler|Q6 4
Pitch|matches|Q7 9
答案 0 :(得分:2)
已更新以反映所需输出格式的变化
试试这个:
with open('input1.txt', 'rb') as file1:
file1_data = dict(line.split(None, 2)[1::-1] for line in file1 if line.strip())
with open('input2.txt', 'rb') as file2, open('output.txt', 'wb') as outputfile:
output = csv.writer(outputfile, delimiter='|')
for line in file2:
row = line.strip().split('|')
key, n = row[0], ' '+row[1].split(' ')[1]
if key in file1_data:
row = [row[0], row[1][:row[1].find(' ')], file1_data[key] + n]
output.writerow(row)
print row