1

我编写了一个脚本来处理以 '>' 开头的生物识别文件,但现在我有一个没有 '>' 的相同文本文件,我更改了我的脚本但它不显示输出。这是我的脚本

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)

这是输入1:

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
4

1 回答 1

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
于 2013-06-26T13:04:13.273 回答