1

我正在尝试制作一个主题列表以供另一个项目使用,并且我将主题存储在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()
4

2 回答 2

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)
于 2016-07-30T18:30:31.947 回答
0

您可以将主题存储在一组中。集合是唯一项目的集合。

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

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

>>> 'Banjo' in topics
True

您通过以下方式将新事物添加到集合中.add()

topics.add('Iceskating')
>>> topics
set(['Banjo','Guitar', 'Piano', 'Iceskating'])

Python 3 文档集在这里。套装教程页面在这里

于 2016-07-30T18:27:06.797 回答