#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Get a summary of the TEXT-format document"""
def get_summary(text, count):
u"""Get the first `count` characters from `text`
>>> text = u'Welcome 这是一篇关于Python的文章'
>>> get_summary(text, 12) == u'Welcome 这是一篇'
True
"""
assert(isinstance(text, unicode))
return text[0:count]
if __name__ == '__main__':
import doctest
doctest.testmod()
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Get a raw summary of the HTML-format document"""
from HTMLParser import HTMLParser
class SummaryHTMLParser(HTMLParser):
"""Parse HTML text to get a summary
>>> text = u'<p>Hi guys:</p><p>This is a example using SummaryHTMLParser.</p>'
>>> parser = SummaryHTMLParser(10)
>>> parser.feed(text)
>>> parser.get_summary(u'...')
u'<p>Higuys:Thi...</p>'
"""
def __init__(self, count):
HTMLParser.__init__(self)
self.count = count
self.summary = u''
def feed(self, data):
"""Only accept unicode `data`"""
assert(isinstance(data, unicode))
HTMLParser.feed(self, data)
def handle_data(self, data):
more = self.count - len(self.summary)
if more > 0:
# Remove possible whitespaces in `data`
data_without_whitespace = u''.join(data.split())
self.summary += data_without_whitespace[0:more]
def get_summary(self, suffix=u'', wrapper=u'p'):
return u'<{0}>{1}{2}</{0}>'.format(wrapper, self.summary, suffix)
if __name__ == '__main__':
import doctest
doctest.testmod()
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Get a raw summary of the HTML-format document"""
import re
def get_summary(text, count, suffix=u'', wrapper=u'p'):
"""A simpler implementation (vs `SummaryHTMLParser`).
>>> text = u'<p>Hi guys:</p><p>This is a example using SummaryHTMLParser.</p>'
>>> get_summary(text, 10, u'...')
u'<p>Higuys:Thi...</p>'
"""
assert(isinstance(text, unicode))
summary = re.sub(r'<.*?>', u'', text) # key difference: use regex
summary = u''.join(summary.split())[0:count]
return u'<{0}>{1}{2}</{0}>'.format(wrapper, summary, suffix)
if __name__ == '__main__':
import doctest
doctest.testmod()
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有