0

我知道这应该很简单,但是由于我是 python 新手,所以在向文件添加值和列时遇到了一些问题。我有两个文件,我想找到匹配的行,如果一行匹配我想要一个值为 1 的新列,如果不匹配应该得到 0。这应该写在 file-1 或 outPut 中。我在添加值时遇到问题。

直到现在我的代码:

# -*- coding: utf8 -*-

f1 = open('text-1.txt', 'r')
f2 = open('text-2.txt', 'r')

fileOne= f1.readlines()
fileTwo = f2.readlines()

outPut = open('output.txt', 'w')

for x,y in zip(fileOne,fileTwo):
    if x==y:
        outPut.write("\t".join(x) + 1)

    else:
        outPut.write("\t".join(x) + 0)


f1.close()
f2.close()
outPut.close

有什么建议或有更简单的方法吗?

谢谢

4

1 回答 1

1

正如您现在所拥有的,您的代码会产生错误:TypeError: cannot concatenate 'str' and 'int' objects. 执行此操作时会发生此错误"\t".join(x) + 1,因为 的结果join是一个字符串,并且1是一个整数。您应该将数字括在引号中:outPut.write("\t".join(x) + "1")

现在你的代码运行了。使用这些文件作为输入:

text-1.txt

foo
bar
baz

text-2.txt

qux
bar
qux

输出是:

f   o   o   
0b  a   r   
1b  a   z0

这可能不是您想要的。我猜你想要每行最初出现的样子,然后是一个制表符,然后是一个 1 或 0。如果这是你想要的,那就outPut.write("\t".join(x) + "1")不是这样做的方法。"\t".join(x)在原始文本的每个字符之间插入一个制表符。如果你想要未修改的文本加上一个制表符加上一个数字,那么就做outPut.write(x + "\t1").

现在的输出是:

foo
    0bar
    1baz    0

这更接近 - 每个字符之间不再有一个制表符,但数字出现在错误的行上。这是因为x是原始行的内容,包括结尾的换行符。如果您希望数字出现在换行符之前,那么您必须去掉换行符,并在末尾添加一个新行:outPut.write(x.rstrip() + "\t1\n")

f1 = open('text-1.txt', 'r')
f2 = open('text-2.txt', 'r')

fileOne= f1.readlines()
fileTwo = f2.readlines()

outPut = open('output.txt', 'w')

for x,y in zip(fileOne,fileTwo):
    if x==y:
        outPut.write(x.rstrip() + "\t1\n")

    else:
        outPut.write(x.rstrip() + "\t0\n")


f1.close()
f2.close()
outPut.close()

现在的输出是:

foo 0
bar 1
baz 0

符合您规定的要求:text-1 的原始内容,加上一个新列,如果匹配,则值为 1,如果不匹配,则为 0。

于 2013-03-07T18:16:47.723 回答