在python 3.x中提取文本文件的特定部分

问题描述 投票:0回答:1

如何使if语句从文本文件的特定位置读取并在特定点停止然后将其打印出来。例如,打印出一个患者的数据,而不是所有列表。初学者程序员在这里。谢谢

 ID = input("please enter a refernce id to search for the patient : ")
 info = open("data.txt", 'r')
 if ID in info: 
 # This should return only one patient's information not all the text file   
 else:
    print("not in file")
info.close()
python python-3.x python-2.7 notepad
1个回答
0
投票

我们需要知道文件格式化的具体细节以给出确切的答案,但这是一种可能有用的方法。

首先,您的'info'现在只是一个TextIOWrapper对象。你可以通过运行print(type(info))来判断。如果格式只是纯文本,你需要让info = open('data.txt', 'r').read()给你一个文本字符串,或者info = open('data.txt', 'r').readlines()给你一个逐行的文本列表。

假设数据看起来像这样:

Patient: Charlie
Age = 99
Description: blah blah blah
Patient: Judith
Age: 100
Description: blah blah blahs

您可以执行以下操作:

首先,查找并存储您要查找的ID的索引。其次,查找并存储表示新ID的某个字符串的索引。在这种情况下,这就是“患者”这个词。最后,在这两个索引之间返回字符串。

例:

ID = input("please enter a reference id to search for the patient: ")
info = open("data.txt", 'r').read()
if ID in info:
    #find() returns the beginning index of a string
    f = info.find(ID)
    goods = info[f:]
    l = goods.find('Patient')
    goods = goods[:l]
    print(goods)   
else:
    print("not in file")

沿着这些方向的东西应该可以解决问题。根据文件的结构,可能有更好的方法。如果用户输入不够具体,或者患者这个词分散在描述中,那么事情就会出错,但这个想法仍然是一样的。您还应该为输入执行一些错误处理。我希望有所帮助!祝你的项目好运。

© www.soinside.com 2019 - 2024. All rights reserved.