在文本文档中搜索字符串

2024-09-30 18:31:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,想知道我的代码中缺少了什么。你知道吗

我想建立一个类,接收3个字母的机场目的地和出发地,并打印出来,如果它在文本文件中

谢谢你的帮助!你知道吗

class departure:
    def __init__(self, destfrom, destto):
        self.destfrom = destfrom
        self.destto = destto

    def verdest(self,dest):
            flag = 0
            destinations = ["JFK","AMS"]
            for i in destinations:
                if i == dest:
                    flag = i
            return flag
if verdest() in open('airportlist.txt').read():
    print("true")

Tags: 代码inselfifdef字母destflag
3条回答

read将文件的行读入单个字符串。 如果使用readlines,则会得到文件中的行列表。 然后您可以查看这些行中是否有单独的代码。 没有课,就像这样:

def verdest(self, dest):
    flag = 0 # note - not used!
    destinations = open('airportlist.txt').readlines()
    return dest in destinations


if verdest("LGW"):
   print("true")

如果要将两个机场名称存储在类中,并在稍后的文件中查找它们,请按原样保存三个字母的代码,但将文件名内容传递给checking函数?你知道吗

class departure:
    def __init__(self, destfrom, destto):
        self.destfrom = destfrom
        self.destto = destto

    def verdest(self, destinations):
        return self.destfrom in destinations and self.destto in destinations

然后创建一个类并使用它:

places = departure("JFK","AMS") 
    #This makes your class, and remembers the variables in member variables

if places.verdest(open('airportlist.txt').readlines()):
    #In this member function call, places remembers the member variable set up above
    print("true")

现在,您可以在类的__init__方法中读取文件,而不是每次都要检查。你知道吗

verdest()函数调用中缺少参数。你知道吗

你需要做一些改变。if i == dest:正在检查JFK是否等于文件内容,您的意思可能是in。然后你有一个类,但你从来没有初始化它。你知道吗

class departure:
  def __init__(self, destfrom, destto):
    self.destfrom = destfrom
    self.destto = destto

  def verdest(self,dest):
    flag = 0
    destinations = ["JFK","AMS"]
    for i in destinations:
      if i in dest: # change to in
        flag = i
    return flag
d = departure(['BWI'],['AMS'])
f = open('airportlist.txt','r')
flag = d.verdest(f.read()) #find last airport that was in file, could modify this to return list
if flag:
  print("true" + flag)
else:
  print('false')
f.close() #close the file

相关问题 更多 >