【问题标题】:Using html2text and clean some text in Python使用 html2text 并在 Python 中清理一些文本
【发布时间】:2015-10-18 14:42:06
【问题描述】:

我正在使用Html2Text 将 html 代码转换为文本。 效果很好,但我在互联网上找不到很多示例或文档。

我是这样读取用户名的:

text_to_gain = hxs.xpath('//div[contains(@id,"yq-question-detail-profile-img")]/a/img/@alt').extract()
if text_to_gain:
        h = html2text.HTML2Text()
        h.ignore_links = True
        item['author'] = h.handle(text_to_gain[0])
else:
        item['author'] = "anonymous"

但我的输出是这样的:

u'Duncan\n\n'

当我阅读长文本或消息时,使用 \n 很有用,但对于单个字符串或某些我只想保留名称。

'Duncan'

【问题讨论】:

    标签: python string python-2.7 selenium


    【解决方案1】:

    使用strip() 函数。这将删除所有空格。

    >>> a = u'Duncan\n\n'
    >>> a
    u'Duncan\n\n'
    >>> a.strip()
    u'Duncan'
    >>> str(a.strip())
    'Duncan'
    

    【讨论】:

    • 对你来说?奇怪的是 html2text 不使用任何函数来不保留 \n
    • u 只是表示该字符串采用 Unicode 字符编码。参考this
    • 您可以使用str() 函数。可以参考this
    【解决方案2】:

    你也可以这样做,只需删除字符'\n':

    >>> st = 'Duncan\n\n'
    >>> st.replace('\n', '')
    'Duncan'
    >>> 
    

    【讨论】:

      猜你喜欢
      • 2013-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-17
      • 1970-01-01
      • 2021-12-11
      • 2021-12-24
      • 1970-01-01
      相关资源
      最近更新 更多