XML分析关于芬德尔在Python 3中

2024-09-29 23:16:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我们正在用NCBI编写一个API。我们请求的结果是一个XML文件recall,我们使用recall.text对其进行转换。我们使用这个转换后的文件来解析特定段落。然而,尽管我们使用了经典的正则表达式,但我们无法使用counter方法解析20个定义的段落。即使是对单个段落的解析也会导致空列表而不是字符串。在

谢谢你的帮助。在

import requests
import pprint
import re

StringNCBI = "p53" #input("Which gene are you interested in? ")
query = StringNCBI.replace(" ", "+")

baseURL="https://eutils.ncbi.nlm.nih.gov/entrez/eutils/"
search="esearch.fcgi?db=gene&term="+query+"%5BGene%20Name%5D"



call=requests.get(baseURL+search)

resp1=call.text
parse1=re.findall(r'<Id>(.*?)</Id>',resp1)
read1=str(parse1)
read2=read1.replace("'","").replace("[", "")
read3=read2.replace("]","")
#print(read3)

summary="esummary.fcgi?db=gene&id="+read3

recall=requests.get(baseURL+summary)
resp2=recall.text
print(resp2)

print(parse1)

resp3 = resp2.replace('"', "!")
str = str()


counterA = 0
while counterA <= 19:
    #hans = parse1[counterA]
    #print(hans)
    #str0 = re.findall(r'<DocumentSummary uid!'+hans+r'!>(.*?)</DocumentSummary uid=!'+hans+r'!>', resp3)
    str0 = re.compile(b'<DocumentSummary uid!7157!>(.*?)</DocumentSummary>', recall)
    print(str0)
    print()
    counterA = counterA + 1

Tags: textimportrerequestsreplace段落printgene
1条回答
网友
1楼 · 发布于 2024-09-29 23:16:32

为了您自己的利益(和理智),请使用xml解析器来解析xml。在

import xml.etree.ElementTree as ET

xml_string = '''
<eSearchResult>
<Count>49</Count>
<RetMax>20</RetMax>
<RetStart>0</RetStart>
<IdList>
<Id>7157</Id>
<Id>22059</Id>
<Id>24842</Id>
<Id>30590</Id>
</IdList>
<TranslationSet/>
<TranslationStack>
<TermSet>
<Term>p53[Gene Name]</Term>
<Field>Gene Name</Field>
<Count>49</Count>
<Explode>N</Explode>
</TermSet>
<OP>GROUP</OP>
</TranslationStack>
<QueryTranslation>p53[Gene Name]</QueryTranslation>
</eSearchResult>'''

xml = ET.fromstring(xml_string)

ids = [id_node.text for id_node in xml.iter('Id')]
print(ids)
# ['7157', '22059', '24842', '30590']

相关问题 更多 >

    热门问题