【问题标题】:Storing and Printing data from text file in Python在 Python 中存储和打印文本文件中的数据
【发布时间】:2019-12-31 01:30:48
【问题描述】:

我有一个程序可以接受用户的输入,例如; 姓名、年龄和电子邮件。

我将此信息存储在列表 (list1) 中,然后将此列表转换为字符串 (mylist) 并写入如下文本文件:

mylist = str(list1)
with open("StudentRecord.txt",'a') as f:
                f.write(merge+"\n")

这可以很好地写入文件并读取/显示整个文件。

我的问题是:如何在文本文件中搜索特定字符串并从中返回数据。 例如:用户输入姓名,我们在文件中查找该字符串并返回他的年龄。

文本文件格式如下:

James, 29, jimmy@company.com
Anthony, 29, jimmy@company.com
Jason, 29, jimmy@company.com

用户想要查找 Jason 的年龄。

【问题讨论】:

标签: python file-handling


【解决方案1】:

正如 Giovani 在他的评论中所说,对于大型数据集,pandas 将是一个更好的选择。但是,您可以通过列表和列表理解来搜索和检索用户年龄,如下所示;

with open('file.txt') as file:
    data = list(file)    

name = input('Enter a Name: ')

age = [i.split(',')[1].strip() for i in data if name in i][0]

print(f"Name: {name}\nAge: {age}")

Enter a Name: James
Name: James
Age: 29

【讨论】:

    【解决方案2】:

    import re
    name = input("Enter the name\n")
    
    with open("f.txt",'r') as f:
        line=f.readlines()
        for i in line:
            if re.match(name,i):
                age=re.findall(r'\d+',i)
    
    print(f"Age of the {name} is {int(age[0])}")

    我已经用正则表达式找到了搜索字符串对应的年龄

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-04
      • 2021-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-03
      • 2018-12-30
      • 1970-01-01
      相关资源
      最近更新 更多