如何从HTML代码中提取信息

时间:2013-10-23 14:06:15

标签: python

此代码是单行的.html文件,它是从HTML文件中提取的,带有唯一标识符“| Rv0153c |”:

<TR><TD><small style=font-family:courier> >M. tuberculosis H37Rv|Rv0153c|ptbB<br />MAVRELPGAWNFRDVADTATALRPGRLFRSSELSRLDDAGRATLRRLGITDVADLRSSRE<br />VARRGPGRVPDGIDVHLLPFPDLADDDADDSAPHETAFKRLLTNDGSNGESGESSQSIND<br />AATRYMTDEYRQFPTRNGAQRALHRVVTLLAAGRPVLTHCFAGKDRTGFVVALVLEAVGL<br />DRDVIVADYLRSNDSVPQLRARISEMIQQRFDTELAPEVVTFTKARLSDGVLGVRAEYLA<br />AARQTIDETYGSLGGYLRDAGISQATVNRMRGVLLG<br /></small><TR><td><b><big>Blastp: <a href="http://tuberculist.epfl.ch/blast_output/Rv0153c.fasta.out"> Pre-computed results</a></big></b><TR><td><b><big>TransMembrane prediction using Hidden Markov Models: <a href="http://tuberculist.epfl.ch/tmhmm/Rv0153c.html"> TMHMM</a></big></b><base target="_blank"/><TR><td><b><big>Genomic sequence</big></b><br /><br /><form action="dnaseq.php" method="get">

我想编写一个能够从这行.html代码中以给定格式提取给定信息(如下所示)的代码:

>M. tuberculosis H37Rv|Rv0153c|ptbB
MAVRELPGAWNFRDVADTATALRPGRLFRSSELSRLDDAGRATLRRLGITDVADLRSSRE
VARRGPGRVPDGIDVHLLPFPDLADDDADDSAPHETAFKRLLTNDGSNGESGESSQSIND
AATRYMTDEYRQFPTRNGAQRALHRVVTLLAAGRPVLTHCFAGKDRTGFVVALVLEAVGL
DRDVIVADYLRSNDSVPQLRARISEMIQQRFDTELAPEVVTFTKARLSDGVLGVRAEYLA
AARQTIDETYGSLGGYLRDAGISQATVNRMRGVLLG

2 个答案:

答案 0 :(得分:1)

我认为您正在寻找的是一个HTML解析器: Simple HTML and XHTML parser

答案 1 :(得分:1)

您可以使用Python和正则表达式库。

from bs4 import BeautifulSoup
import re
sentence = '<TR><TD><small style=font-family:courier> >M. tuberculosis H37Rv|Rv0153c|ptbB<br />MAVRELPGAWNFRDVADTATALRPGRLFRSSELSRLDDAGRATLRRLGITDVADLRSSRE<br />VARRGPGRVPDGIDVHLLPFPDLADDDADDSAPHETAFKRLLTNDGSNGESGESSQSIND<br />AATRYMTDEYRQFPTRNGAQRALHRVVTLLAAGRPVLTHCFAGKDRTGFVVALVLEAVGL<br />DRDVIVADYLRSNDSVPQLRARISEMIQQRFDTELAPEVVTFTKARLSDGVLGVRAEYLA<br />AARQTIDETYGSLGGYLRDAGISQATVNRMRGVLLG<br /></small><TR><td><b><big>Blastp: <a href="http://tuberculist.epfl.ch/blast_output/Rv0153c.fasta.out"> Pre-computed results</a></big></b><TR><td><b><big>TransMembrane prediction using Hidden Markov Models: <a href="http://tuberculist.epfl.ch/tmhmm/Rv0153c.html"> TMHMM</a></big></b><base target="_blank"/><TR><td><b><big>Genomic sequence</big></b><br /><br /><form action="dnaseq.php" method="get">'   
print re.sub('<[^>]*>', '',  sentence)

HTH。