python,通过坐标从DAS获取序列

时间:2014-03-11 14:13:11

标签: python xml parsing sequence

ucsc DAS server,通过坐标获得DNA序列。

网址:http://genome.ucsc.edu/cgi-bin/das/hg19/dna?segment=chr20:30037432,30038060

示例文件:

<DASDNA>
  <SEQUENCE id="chr20" start="30037832" stop="30038060" version="1.00">
  <DNA length="229">
    gtggcacccaaagatgctggaatctttatggcaaatgccgttacagatgc            
    tccaagaaggaaagagtctatgtttactgcataaataataaaatgtgctg     
    cgtgaagcccaagtaccagccaaaagaaaggtggtggccattttaactgc 
    tttgaagcctgaagccatgaaaatgcagatgaagctcccagtggattccc 
    acactctatcaataaacacctctggctga
  </DNA>
  </SEQUENCE>
</DASDNA>

我想要的是这部分:

    gtggcacccaaagatgctggaatctttatggcaaatgccgttacagatgc            
    tccaagaaggaaagagtctatgtttactgcataaataataaaatgtgctg     
    cgtgaagcccaagtaccagccaaaagaaaggtggtggccattttaactgc 
    tttgaagcctgaagccatgaaaatgcagatgaagctcccagtggattccc 
    acactctatcaataaacacctctggctga

我想从成千上万的这类网址中获取序列部分,我应该怎么做? 我试图将数据写入文件并解析文件,它工作正常,但有没有办法直接解析类似xml的字符串?我尝试了其他帖子的一些例子,但他们没有用。

在这里,我添加了我的解决方案。感谢下面的2个答案。

解决方案1:

def getSequence2(chromosome, start, end):
    base = 'http://genome.ucsc.edu/cgi-bin/das/hg19/dna?segment='
    url = base + chromosome + ':' + str(start) + ',' + str(end)
    doc = etree.parse(url,parser=etree.XMLParser())
    if doc != '':
        sequence = doc.xpath('SEQUENCE/DNA/text()')[0].replace('\n','')
    else:
        sequence = 'THE SEQUENCE DOES NOT EXIST FOR GIVEN COORDINATES'
    return sequence

解决方案2:

def getSequence1(chromosome, start, end):
    base = 'http://genome.ucsc.edu/cgi-bin/das/hg19/dna?segment='
    url = base + chromosome + ':' + str(start) + ',' + str(end)
    xml = urllib2.urlopen(url).read()
    if xml != '':
        w = open('temp.xml', 'w')
        w.write(xml)
        w.close()
        dom = parse('temp.xml')
        data = dom.getElementsByTagName('DNA')
        sequence = data[0].firstChild.nodeValue.replace('\n','')
    else: 
        sequence = 'THE SEQUENCE DOES NOT EXIST FOR GIVEN COORDINATES'
    return sequence

当然,他们需要导入一些必要的库。

2 个答案:

答案 0 :(得分:2)

>>> from lxml import etree
>>> doc = etree.parse("http://genome.ucsc.edu/cgi-bin/das/hg19/dna?segment=chr20:30037432,30038060",parser=etree.XMLParser())
>>> doc.xpath('SEQUENCE/DNA/text()')
['\natagtggcacatgtctgttgtcctagctcctcggggaaactcaggtggga\ngagtcccttgaactgggaggaggaggtttgcagtgagccagaatcattcc\nactgtactccagcctaggtgacagagcaagactcatctcaaaaaaaaaaa\naaaaaaaaaaaaaagacaatccgcacacataaaggctttattcagctgat\ngtaccaaggtcactctctcagtcaaaggtgggaagcaaaaaaacagagta\naaggaaaaacagtgatagatgaaaagagtcaaaggcaagggaaacaaggg\naccttctatctcatctgtttccattcttttacagacctttcaaatccgga\ngcctacttgttaggactgatactgtctcccttctttctgctttgtgtcag\ngtggcacccaaagatgctggaatctttatggcaaatgccgttacagatgc\ntccaagaaggaaagagtctatgtttactgcataaataataaaatgtgctg\ncgtgaagcccaagtaccagccaaaagaaaggtggtggccattttaactgc\ntttgaagcctgaagccatgaaaatgcagatgaagctcccagtggattccc\nacactctatcaataaacacctctggctga\n']

答案 1 :(得分:1)

使用像lxml这样的Python XML解析库,使用该解析器加载XML文件,然后使用选择器(例如使用XPath)来获取所需的节点/元素。