【问题标题】:How to match an exact word in a json soup?如何匹配 json 汤中的确切单词?
【发布时间】:2019-10-23 01:10:54
【问题描述】:

我正在解析从 url 抓取的患者元数据,并且我正在尝试访问 'PatientID' 字段。不过,还有一个'OtherPatientIDs'字段,被我搜到了。

我尝试过使用正则表达式,但我不清楚如何匹配 EXACT 字符串或如何将其合并到我的代码中。

所以目前,我已经完成了:

response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")

PatientID = "PatientID"

lines = soup.decode('utf8').split("\n")
for line in lines:
    if "PatientID" in line:
        PatientID = line.split(':')[1].split('\"')[1].split('\"')[0]
        print(PatientID)

成功找到 PatientID 和 OtherPatientIDs 字段的值。如何指定我只需要 PatientID 字段?

编辑: 我被要求举一个例子来说明我从 response.text 中得到的东西,它的形式是:

{
    "ID" : "shqowihdojcoughwoeh"
    "LastUpdate: "20190507"
    "MainTags" : {
         "OtherPatientIDs" : "0304992098"
         "PatientBirthDate" : "29/04/1803"
         "PatientID" : "92879837"
         "PatientName" : "LASTNAME^FIRSTNAME"
     },
     "Type" : "Patient"
}

【问题讨论】:

  • 您介意发布一个示例,说明您使用 response.text 得到的结果吗?
  • 您的数据看起来像 json,您是否考虑过尝试将其解析为 json 而不是 html?然后你可以做json['MainTags']['PatientID'] 之类的事情,只得到你需要的东西。

标签: python json string match


【解决方案1】:

为什么不改用json 库?

import json
import requests

response = requests.get(url)
data = json.loads(response.text)

print(data['MainTags']['PatientID'])

【讨论】:

    猜你喜欢
    • 2023-01-16
    • 2016-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多