Сколько квадратных корней Вы действительно выполняете? Вы пытаетесь записать некоторый 3D графический механизм в Python? В противном случае тогда, почему идут с кодом, который является загадочным по коду, который легко считать? Разница во времени, были бы меньше, чем кто-либо мог заметить в примерно любом приложении, которое я мог предвидеть. Я действительно не означаю подавлять Ваш вопрос, но кажется, что Вы немного заходите слишком далеко с преждевременной оптимизацией.
Try not to laugh, but:
class TextFormatter:
def __init__(self,lynx='/usr/bin/lynx'):
self.lynx = lynx
def html2text(self, unicode_html_source):
"Expects unicode; returns unicode"
return Popen([self.lynx,
'-assume-charset=UTF-8',
'-display-charset=UTF-8',
'-dump',
'-stdin'],
stdin=PIPE,
stdout=PIPE).communicate(input=unicode_html_source.encode('utf-8'))[0].decode('utf-8')
I hope you've got lynx!
Well, it depends how good the solution has to be. I had a similar problem, importing hundreds of old html pages into a new website. I basically did
# remove all that crap around the body and let BS fix the tags
newhtml = "<html><body>%s</body></html>" % (
u''.join( unicode( tag ) for tag in BeautifulSoup( oldhtml ).body.contents ))
# use html2text to turn it into text
text = html2text( newhtml )
and it worked out, but of course the documents could be so bad that even BS can't salvage much.
BeautifulSoup плохо справится с искаженным HTML. А как насчет некоторого regex-fu?
>>> import re
>>>
>>> html = """<p>This is paragraph with a bunch of lines
... from a news story.</p>"""
>>>
>>> pattern = re.compile('(?<=p>).+(?=</p)', re.DOTALL)
>>> pattern.search(html).group()
'This is paragraph with a bunch of lines\nfrom a news story.'
Затем вы можете собрать список допустимых тегов, из которых вы хотите извлечь информацию.