【问题标题】:Comparing a file to another file比较一个文件和另一个文件
【发布时间】:2016-01-31 21:36:21
【问题描述】:
import sys
import os
import glob
directorylist = ["A", "B", "C", "D"]

for directory in directorylist:
    for file in glob.glob(os.path.join(directory, "tobecompared(*).txt")):
        with open(file) as f:
                a=0
                fdata = f.readlines()
                for line in fdata:
                    with open ("/Users/Student/Desktop/folder/pool.txt", "r") as pool:
                        if line in pool:
                            a=a+1
                print a

我想将文本文件(tobecompared1.txt、tobecompared2.txt)中的行与另一个文本文件(pool.txt)中的行进行比较。 该文件夹包含文件夹 A、B、C 和 D。 pool.txt 位于文件夹中,而 tobecompared(*).txt 文件位于 A、B、C 目录中。此代码旨在打印编号。原始池中存在的待比较文本文件中的行数。

此代码重复打印 0,所以我猜测循环中存在将 a 的值增加 1 的问题。 真正针对的是:

说 pool.txt 是

A
B
C
D

A中的tobecompared(01).txt是

A
A
F
H
C
B

A中的tobecompared(02).txt是

A
B
C

B中的tobecompared(01).txt是

G
D
C

输出将是:

4
3
2

【问题讨论】:

    标签: python file if-statement compare line


    【解决方案1】:

    您正在文件对象中查找字符串。这种情况永远不会成真。替换:

    if line in pool: 
        a=a+1
    

    与:

    for line2 in pool:
        if line.rstrip() == line2.rstrip():
            a += 1
    

    【讨论】:

    • 这会匹配相同的行,或者如果有相似的行有一些相同的单词,这也算吗?线条相同很重要...
    • 这会将tobeCompared中的每一行与pool.txt中的每一行进行比较;只有当它们相同时,计数器才会递增。试试看
    猜你喜欢
    • 2016-01-03
    • 2015-06-22
    • 1970-01-01
    • 1970-01-01
    • 2019-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-30
    相关资源
    最近更新 更多