2

我想比较两个txt文件的所有行,但是当我运行代码时它只响应几个结果,循环没有有效运行,似乎错过了File1中的很多行,只出现了File1的第一行。

问题:

我的循环有什么问题吗?非常感谢!</p>

def compareLines(filename1,filename2):

    File1=open(filename1,'r')
    File2=open(filename2,'r')
    File3=open("Result.txt",'w')

    finalList=[]
    for line1 in File1:
        for line2 in File2:
            set1=set(line1.split(" "))
            set2=set(line2.split(" "))
            print line1
            print line2
            similarNumber=len(set1.intersection(set2))/float(len(set1.union(set2)))
            File3.write('Simmilar rate:'+str(similarNumber)+' '+str(len(set1.intersection(set2)))+" words in incoindence\n")
            finalList.append(similarNumber)

    File1.close()
    File2.close()
    File3.close()

    os.remove(filename1)
    os.remove(filename2)

    return finalList
4

2 回答 2

2

File2您应该在内部循环中重新打开或使用file.seek跳转到文件的开头,因为在第一次迭代后,文件指针位于File2.

帮助file.seek

>>> print file.seek.__doc__
seek(offset[, whence]) -> None.  Move to new file position.

Argument offset is a byte count.  Optional argument whence defaults to
0 (offset from start of file, offset should be >= 0); other values are 1
(move relative to current position, positive or negative), and 2 (move
relative to end of file, usually negative,....
于 2013-08-29T15:30:15.707 回答
0

感谢上面的回答。特别感谢Nisan.H和Ashwini Chaudhary,在你们的帮助下我已经解决了这个问题,只在“for line2 in File2”之前添加一行~~~

def 比较行(文件名 1,文件名 2):

File1=open(filename1,'r')
File2=open(filename2,'r')
File3=open("Result.txt",'w')

finalList=[]

for line1 in File1:
    File2.seek(0)
    for line2 in File2:
        set1=set(line1.split(" "))
        set2=set(line2.split(" "))
        print line1
        print line2
        similarNumber=len(set1.intersection(set2))/float(len(set1.union(set2)))
        File3.write('Simmilar rate:'+str(similarNumber)+' '+str(len(set1.intersection(set2)))+" words in incoindence\n")
        finalList.append(similarNumber)

File1.close()
File2.close()
File3.close()

os.remove(filename1)
os.remove(filename2)

return finalList
于 2013-08-30T00:44:20.067 回答