首页 > 解决方案 > 从用户那里获取输入并在文本文件中搜索并返回该点在文本文件中的位置

问题描述

我正在尝试在文本文件中搜索一个字符串(由用户输入),如果该字符串存在于文本文件中,那么它将返回它的位置(文件中的位置)

我在 python 中使用寻找和告诉文本文件的方法

def search(self,identity):
    with open("dbase.txt", 'r') as dbase:
      find = dbase.readline()
      while str.casefold(find) == str.casefold(identity):
          pos = dbase.tell() 
          find = dbase.readline()
          return pos

完整代码:

class app:
    ''' class that takes the data and save it
    into a text file name dbase.txt'''
    def get_data(self):
        self.name = input("Name : ")
        self.add = input("Address : ")
        self.mob = input("Mobile : ")
    def write_data(self):
        dbase = open("dbase.txt",'a')
        dbase.write(self.name+"\n")
        dbase.write(self.add+"\n")
        dbase.write(self.mob+"\n")
        dbase.close()
    def read_data(self,pos):
        dbase = open("dbase.txt",'r')
        dbase.seek(pos)
        self.name = dbase.readline()
        self.add = dbase.readline()
        self.mob = dbase.readline()  
        print(self.name)
        print(self.add)
        print(self.mob)
    def search(self,identity):
            data = open("dbase.txt", 'r').read()
            desired_string = identity
            if desired_string in data:
                pos = data.find(desired_string)
                return pos
            else:
                print("The desired string does not exist in the file")

call = app()
f = input("Enter :")
pos = call.search(f)
call.read_data(pos)

identity 代表我在这个函数中作为参数传递的用户输入,我想在文件中匹配这个身份,我在变量 find 中提取文件数据,所以如果 find 等于 identity 那么我想返回它的当前位置在文件中但它不起作用,我曾尝试在 while 循环中打印一些东西,例如 print("x") 或其他东西来检查天气 While 循环条件是否为真,因为如果它为真,那么它将打印“ x”,但它没有打印出任何我得出的结论,即 while 循环条件为假,因此我认为故障出在线路上。

while str.casefold(find) == str.casefold(identity):

但我不明白为什么会这样,因为我输入的字符串实际上存在于文件中。

标签: pythonpython-3.x

解决方案


data = open("filename.ext", 'r').read().replace("\n", "\n\n")

desired_string = "apples"

if desired_string in data:
    index = data.find(desired_string)
else:
    print("The desired string does not exist in the file")

上面的代码将在文件中搜索所需的字符串,如果存在,它的第一次出现的索引将存储在变量中index。否则将打印文件中不存在所需的字符串。


推荐阅读