【问题标题】:Compare two files .txt and validate if all elements of file 1 is on the file 2比较两个文件 .txt 并验证文件 1 的所有元素是否都在文件 2 上
【发布时间】:2020-05-17 03:41:27
【问题描述】:

我想比较 2 个文件并显示它是否正常(验证)。 这里有一张小图来描述我想做的事情:

Description

def open_file_txt(file_name):  

    with open(file_name, 'r') as f:
        x = f.readlines()

    return x

def validation(file_name1, file_name2):

    file1 = open_file_txt(file_name1)
    file2 = open_file_txt(file_name2)

    for elem in file1:
        for elem2 in file2:
            #### code 

我不知道我是否开始好,但我想像这样的结构......

【问题讨论】:

  • 在您的示例中,您希望逐行比较文件。并且每个文件的行都按字母顺序排序,并且是唯一的(没有重复),因此例如Test A, TestD, TestF 使用换行符而不是逗号。因此,您可以将它们存储在 Python set 中,甚至不需要 collections.Counter(一个项目不能多次出现)。

标签: python


【解决方案1】:

readlines() 返回一个列表,因此一旦您拥有两个列表,您就可以使用set(lst1).intersection(lst2) 获取两个列表共有的元素。此外,由于您想检查 lst1 的所有元素是否都在 lst2 中,您可以执行 set(lst1).difference(lst2) 并确保结果为空,因为这会返回 lst1 中未在 lst2 中找到的元素。

在此示例中,lst1lst2 是您的 readlines() 调用中的两个列表。

希望对您有所帮助。

【讨论】:

    【解决方案2】:

    正确的使用方法是set.issubset

    set(file1).issubset(file2)
    

    注意 issubset 接受一个列表(至少在 python 3.7 中),所以你只需要转换一个列表。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-02
      • 1970-01-01
      • 1970-01-01
      • 2022-11-02
      • 2020-11-06
      • 1970-01-01
      相关资源
      最近更新 更多