0

I have a text file. I want to get the lines that contain a file-name only if the file-name is a .doc or a .pdf type file.

For example,

<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>

using python re.findall() I want to get the following lines.

<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>

Can any body please tell me any scalable way to define the pattern in the re.findall()?

jamylak
  • 128,818
  • 30
  • 231
  • 230
mxant
  • 17
  • 3

3 Answers3

2

You can use this regex:

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

Output:

>>> 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>']
jvallver
  • 2,230
  • 2
  • 11
  • 20
1

Something like this:

>>> 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>'
]
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
1

You can use both BeautifulSoup and re.

import BeautifulSoup
import re

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

with class your upper level header in the html code.

kiriloff
  • 25,609
  • 37
  • 148
  • 229