0

我有一个文本文件。仅当文件名是 .doc 或 .pdf 类型文件时,我才想获取包含文件名的行。

例如,

<TR><TD ALIGN="RIGHT">4.</TD>
<TD ALIGN="LEFT" VALIGN="TOP" WIDTH=50%><a href="ABC.pdf"> On Complex Analytic Manifolds</a></TD>
<TD ALIGN="LEFT" VALIGN="TOP" WIDTH=72>L. Sam</TD>
</TR>
<TR><TD ALIGN="RIGHT">5.</TD>
<TD ALIGN="LEFT" VALIGN="TOP" WIDTH=50%><a href="DEF.doc"> On the Geometric theory of Fields</a>*</TD>
<TD ALIGN="LEFT" VALIGN="TOP" WIDTH=72>G.K. Ram</TD>
</TR>

使用 pythonre.findall()我想得到以下几行。

<TD ALIGN="LEFT" VALIGN="TOP" WIDTH=50%><a href="ABC.pdf"> On Complex Analytic Manifolds</a></TD>
<TD ALIGN="LEFT" VALIGN="TOP" WIDTH=50%><a href="DEF.doc"> On the Geometric theory of Fields</a>*</TD>

任何人都可以告诉我任何可扩展的方式来定义 re.findall() 中的模式吗?

4

3 回答 3

2

您可以使用此正则表达式:

(.*?<a\shref=[\"']\w+(?:\.doc|\.pdf)[\"']>.*)

输出:

>>> html = """<TR><TD ALIGN="RIGHT">4.</TD>
... <TD ALIGN="LEFT" VALIGN="TOP" WIDTH=50%><a href="ABC.pdf"> On Complex Analytic Manifolds</a></TD>
... <TD ALIGN="LEFT" VALIGN="TOP" WIDTH=72>L. Sam</TD>
... </TR>
... <TR><TD ALIGN="RIGHT">5.</TD>
... <TD ALIGN="LEFT" VALIGN="TOP" WIDTH=50%><a href="DEF.doc"> On the Geometric theory of Fields</a>*</TD>
... <TD ALIGN="LEFT" VALIGN="TOP" WIDTH=72>G.K. Ram</TD>
... </TR>"""
>>> re.findall("(.*?<a\shref=[\"']\w+(?:\.doc|\.pdf)[\"']>.*)", html)
['<TD ALIGN="LEFT" VALIGN="TOP" WIDTH=50%><a href="ABC.pdf"> On Complex Analytic Manifolds</a></TD>', '<TD ALIGN="LEFT" VALIGN="TOP" WIDTH=50%><a href="DEF.doc"> On the Geometric theory of Fields</a>*</TD>']
于 2013-05-15T06:55:31.653 回答
1

您可以同时使用BeautifulSoupre

import BeautifulSoup
import re

lines = soup.findAll('href', text = re.compile('your regex here'), attrs = {'class' : 'text'})

在 html 代码中使用class您的上层标题。

于 2013-05-15T07:36:17.357 回答
1

像这样的东西:

>>> strs="""<TR><TD ALIGN="RIGHT">4.</TD>
<TD ALIGN="LEFT" VALIGN="TOP" WIDTH=50%><a href="ABC.pdf"> On Complex Analytic Manifolds</a></TD>
<TD ALIGN="LEFT" VALIGN="TOP" WIDTH=72>L. Sam</TD>
</TR>
<TR><TD ALIGN="RIGHT">5.</TD>
<TD ALIGN="LEFT" VALIGN="TOP" WIDTH=50%><a href="DEF.doc"> On the Geometric theory of Fields</a>*</TD>
<TD ALIGN="LEFT" VALIGN="TOP" WIDTH=72>G.K. Ram</TD>
</TR>"""

>>> [x for x in strs.splitlines() if re.search(r"[a-zA-Z0-9]+\.(pdf|doc)",x)]
['<TD ALIGN="LEFT" VALIGN="TOP" WIDTH=50%><a href="ABC.pdf"> On Complex Analytic Manifolds</a></TD>',
 '<TD ALIGN="LEFT" VALIGN="TOP" WIDTH=50%><a href="DEF.doc"> On the Geometric theory of Fields</a>*</TD>'
]
于 2013-05-15T06:53:20.177 回答