L
L
Lyova Matyushkin2011-03-25 13:19:25
Python
Lyova Matyushkin, 2011-03-25 13:19:25

Python - Efficiently capturing a string with a specific number?

From a large number of html pages of the same type, you need to pick up only one line with the same number, say, eleventh. How can this be done most efficiently, faster than:

<font color="black"><a href="http://s-c.me/15443/s">Copy Source</a> | <a href="http://s-c.me/15443/h">Copy HTML</a><br/>
<font color="#0000ff">for</font> i, line <font color="#0000ff">in</font> <b>enumerate</b>(page):<br/>
    <font color="#0000ff">if</font> i == <font color="#008000">10</font>:<br/>
        s = line + <font color="#008000">'\n'</font><br/>
        outfile.write(s)<br/>
    <font color="#0000ff">elif</font> i &gt; <font color="#008000">10</font>:<br/>
        <font color="#0000ff">break</font><br/>
 <br/>
</font>

Answer the question

In order to leave comments, you need to log in

4 answer(s)
S
Sergey Lerg, 2011-03-25
@Lerg

There is another way, I don’t know how much faster, but shorter for sure:

B
bekbulatov, 2011-03-25
@bekbulatov

If page is not a list, then convert to this type

outfile.write('%s\n' % list(page)[10])

S
savados, 2011-03-25
@savados

page.splitlines()[10]

A
alexandris, 2011-03-25
@alexandris

Why read the entire page when you can only read the essentials:
>>> import urllib2
>>> p = urllib2.urlopen('http://habrahabr.ru/')
>>> for i in xrange(10):
... p.readline()
>>> print p.readline()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question