【问题标题】:How can I print specific parts of a text file in python?如何在 python 中打印文本文件的特定部分?
【发布时间】:2020-02-10 12:24:53
【问题描述】:

我有一个文本文件,例如一个包含多个姓名 + 相关电话号码/年龄的数据库:

姓名 - 鲍勃

姓 - 詹金斯

年龄 - 32


名字 - 哈利

姓氏 - 海滩

年龄 - 26


名字 - 伊森

姓-霍尔

年龄 - 40

我在 python 中输入了一个名为“搜索”的内容,然后在文本文件中查找任何匹配项。我怎样才能让它打印那个人的信息。例如,在输入中我输入了“Harry”,因此它会在文本文件中搜索任何说“Harry”的行并打印他们的姓名、姓氏和年龄。

【问题讨论】:

  • 是的,你可以。去做吧。
  • 但是使用真实数据库(即 sqlite)可能更有用 - 它可以按姓名、年龄、年龄、年龄或年龄然后一些值进行搜索,名称只有部分文本,名称没有没有一些文字,“Harry 年龄超过 30 岁”等。
  • 数据是如何存储的?在.txt 文件或list 或dict?
  • @Ch3steR 它存储在 .txt 文件中
  • @Poseidon1000 您的.txt 文件看起来如何?和你在问题中提到的一样吗?

标签: python


【解决方案1】:

这是一个可以将您的文本转换为字典的脚本。有了它,您可以轻松搜索各种参数。

with open('db.txt') as f:
    file = f.readlines()
db = []
for i in range(0, len(file), 4):
    d = {}
    d[file[i].split(" - ")[0]]=file[i].split(" - ")[1][:-1]
    d[file[i+1].split(" - ")[0]]=file[i+1].split(" - ")[1][:-1]
    d[file[i+2].split(" - ")[0]]=file[i+2].split(" - ")[1][:-1]
    db.append(d)
print(db)

db 看起来像

[{'Name': 'Bob', 'Surname': 'Jenkins', 'Age': '32'}, {'Name': 'Harry', 'Surname': 'Beach', 'Age': '26'}, {'Name': 'Ethan', 'Surname': 'Hall', 'Age': '4'}]

作为旁注,我强烈建议使用一些数据库,如 SQLite (SQL)、TinyDB (NoSQL) 或哎呀,只是一个普通的 JSON 文件,而不是文本文件。

【讨论】:

    【解决方案2】:

    这应该可行:

    lookup = 'Bob'
    a=[]
    b=[]
    myFile=open('myFile.txt', 'r')
    num_lines = sum(1 for line in open('myfile.txt'))
    lines = myFile.read().splitlines()
    
    for i in range(num_lines):
        if lookup in lines[i] and "Name" in lines[i]:
            a.append(lookup)
            b.append(i)
    
    for i in range (len(a)):
        print("Name: "+a[0])
        print(lines[b[0]+2])
        print(lines[b[0]+4])
    

    只需将 lookup 变量更改为所需的名称,它就会打印出姓名、姓氏和年龄。

    如果文本文件完全符合您的问题,则此方法有效。姓名、姓氏和年龄之间的空格数需要为 1。

    【讨论】:

      【解决方案3】:

      搜索代码

      import re
      
      def lookup(filename, findname):
        " Looks up findname in text file "
        with open(filename, 'r') as f:
          for line in f:
            # match line of the form: Name - {findname}
            # make case insensitive by making first letter lowercase, other letters lower case
            if re.match(f'^Name - {findname.title()}', line): 
              name = line.rstrip().split()[-1]   # Get name line
              surname = next(f).rstrip().split()[-1]   # next line is surname
              age = next(f).rstrip().split()[-1]       # next line is age
              return name, surname, age   # result
              break
          else:
            return None                   # Not found in text file
      

      测试代码

      混合使用大小写名称拼写来显示搜索不区分大小写

      for search_name in ['Bob', 'bob', 'mary', 'harry']:
        found = lookup('db.txt', search_name)
        print(f"Search Result for {search_name}")
        if found:
          name, surname, age = found
          print(f"Name: {name} {surname}\nAge {age}")
        else:
          print(f"{search_name} not found")
      
        print("")
      

      文件 db.txt

      Name - Bob
      Surname - Jenkins
      Age - 32
      
      Name - Harry
      Surname - Beach
      Age - 26
      
      Name - Ethan
      Surname - Hall
      Age - 40
      

      输出

      Search Result for Bob
      Name: Bob Jenkins
      Age 32
      
      Search Result for bob
      Name: Bob Jenkins
      Age 32
      
      Search Result for mary
      mary not found
      
      Search Result for harry
      Name: Harry Beach
      Age 26
      

      【讨论】:

        猜你喜欢
        • 2020-11-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多