【问题标题】:Replace a named comment using BS4使用 BS4 替换命名评论
【发布时间】:2018-03-12 16:29:42
【问题描述】:

假设我有以下:

<!--NAMED COMMENT<trans-unit id="1" reformat="yes">
<source>foo</source>
<target>bar</target>
</trans-unit>-->

我想回来

<trans-unit id="1" reformat="yes">
<source>foo</source>
<target>bar</target>
</trans-unit>

我似乎无法在问题中剥离 cmets。我可以访问这些 cmets:

soup = BeautifulSoup(xlf, "lxml")
comments = soup.find_all(text=lambda text: isinstance(text, Comment))
for comment in comments:
    print(comment)

但不能返回带有这些更改的增补对象。任何帮助将不胜感激。

【问题讨论】:

  • 那么,您想从您的代码正在打印的字符串中删除NAMED COMMENT 部分吗?

标签: python python-3.x beautifulsoup


【解决方案1】:

您的代码将其打印为输出:

NAMED COMMENT<trans-unit id="1" reformat="yes">
<source>foo</source>
<target>bar</target>
</trans-unit>

如果您想从字符串中删除NAMED COMMENT 部分,您可以简单地使用strip('NAMED COMMENT')。像这样的:

comments = soup.find_all(text=lambda text: isinstance(text, Comment))
for comment in comments:
    print(comment.strip('NAMED COMMENT'))

输出:

<trans-unit id="1" reformat="yes">
<source>foo</source>
<target>bar</target>
</trans-unit>

如果您想将这些更改保存在列表本身中,您可以使用列表推导。

comments = [x.strip('NAMED COMMENT') for x in soup.find_all(text=lambda text: isinstance(text, Comment))]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-21
    • 1970-01-01
    • 1970-01-01
    • 2015-11-11
    • 1970-01-01
    • 2014-04-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多