检查文件中的数据是否有重复项(Python)

时间:2016-07-30 18:10:40

标签: python python-3.x duplicates keyword-search

我正在尝试为另一个项目制作一个主题列表,我将这些主题存储在Topics.txt中。但是,当主题存储在文件中时,我不希望重复主题。因此,当我将主题保存到Topics.txt文件时,我还将它们保存到Duplicates.txt文件中。我想要做的是创建一个条件语句,如果主题在Topics.txt中,则不会向Duplicates.txt添加主题。我的问题是,我不知道如何创建一个条件语句,可以检查该主题是否列在Duplicates.txt中。如果您扫描诸如“音乐”之类的关键字,看到“电子音乐”包含单词“音乐”,则可能会出现问题。

Entry = input("Enter topic: ")
Topic = Entry + "\n"
Readfilename = "Duplicates.txt"
Readfile = open(Readfilename, "r")
Readdata = Readfile.read()
Readfile.close()
if Topic not in Duplicates:
    Filename = "Topics.txt"
    File = open(Filename, "a")
    File.append(Topic)
    File.close()
    Duplicate = Topic + "\n"
    Readfile = open(Readfilename, "a")
    Readfile.append(Topic)
    Readfile.close()

2 个答案:

答案 0 :(得分:1)

您可以逐行读取文件,这将导致像这样的解决方案

Entry = input("Enter topic: ")
Topic = Entry + "\n"
Readfilename = "Duplicates.txt"
found=False
with open(Readfilename, "r") as Readfile:
    for line in Readfile:
        if Topic==line:
            found=True
            break # no need to read more of the file

if not found:
    Filename = "Topics.txt"
    with open(Filename, "a") as File:
        File.write(Topic)

    with open(Readfilename, "a") as Readfile:
        Readfile.write(Topic)

答案 1 :(得分:0)

您可以将主题存储在一个集合中。一套是独特物品的集合。

topics = {'Banjo', 'Guitar', 'Piano'}

您可以使用以下方式检查会员资格:

>>> 'Banjo' in topics
True

您可以通过.add()

向集合添加新内容
topics.add('Iceskating')
>>> topics
set(['Banjo','Guitar', 'Piano', 'Iceskating'])

集合here上的Python 3文档。集合上的教程页面为here