python - 比较两个文本文件未给出所需结果

标签 python python-2.7

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

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

但是现在我的input2文件更改为

输入2:

Bat|batsman 8
Ball|bowler 4
Pitch|matches 9

所需的输出

Bat|batsman|Q5 8
Ball|bowler|Q6 4
Pitch|matches|Q7 9

最佳答案

已更新以反射(reflect)所需输出格式的更改

试试这个:

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

关于python - 比较两个文本文件未给出所需结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17320133/

相关文章:

python - 避免在 Python 模块 Sympy 中对参数进行排序

python - 我的第一个自述文件在 pypi.python.org 上未格式化

python - 如何处理多个异常?

python-2.7 - 为什么在 Python 中 (5 % 2) 和 (-5 % 2) 都是一样的

python - 没有名为 setuptools 的模块

python - 无法在Jupyter笔记本(Anaconda)上导入cv2

django - 如何修改django-celery web界面进行周期性调度

python - 枚举可以用在递归中吗?这个例子的递归是什么?

python - 我如何用正则表达式来表示 "divide"单词?

python - "undo"numpy.delete, numpy.insert?