【问题标题】:Python - Find text using beautifulSoup then replace in original soup variablePython - 使用 beautifulSoup 查找文本,然后替换原始汤变量
【发布时间】:2013-02-09 23:40:36
【问题描述】:
commentary = soup.find('div', {'id' : 'live-text-commentary-wrapper'})
findtoure = commentary.find(text = re.compile('Gnegneri Toure Yaya')).replace('Gnegneri      Toure Yaya', 'Yaya Toure')

评论包含需要更改为 Yaya Toure 的 Gnegneri Toure Yaya 的各种实例。

findAll() 不起作用,因为 findtoure 是一个列表。

我遇到的另一个问题是这段代码只是找到它们并将它们替换为一个名为 findtoure 的新变量,我需要在原始汤中替换它们。

我想我只是从错误的角度看待这个问题。

【问题讨论】:

  • @MartijnPieters 我希望你的晚餐有一道美丽的汤;),但如果你不记得,我不能怪你。

标签: python beautifulsoup


【解决方案1】:

只是.replace(),你无法为所欲为。来自BeautifulSoup documentation on NavigableString

您不能就地编辑字符串,但可以使用 replace_with() 将一个字符串替换为另一个字符串。

这正是您需要做的;获取每个匹配项,然后在包含的文本上调用 .replace() 并将原来的替换为:

findtoure = commentary.find_all(text = re.compile('Gnegneri Toure Yaya'))
for comment in findtoure:
    fixed_text = comment.replace('Gnegneri Toure Yaya', 'Yaya Toure')
    comment.replace_with(fixed_text)

如果您想进一步使用这些 cmets,您需要重新查找:

findtoure = commentary.find_all(text = re.compile('Yaya Toure'))

或者,如果您只需要生成的 字符串(因此 Python str 对象,而不是 NavigableString 对象仍然连接到 BeautifulSoup 对象),只需收集 fixed_text对象:

findtoure = commentary.find_all(text = re.compile('Gnegneri Toure Yaya'))
fixed_comments = []
for comment in findtoure:
    fixed_text = comment.replace('Gnegneri Toure Yaya', 'Yaya Toure')
    comment.replace_with(fixed_text)
    fixed_comments.append(fixed_text)

【讨论】:

  • unicode 语句出错。那是哪个包的?它适用于 3.7+ 吗?
  • @blissweb:这是使用 Python 2 语法。我已经为 Python 3 更新了它。
  • 如何在循环中打印新文本?
猜你喜欢
  • 2014-10-28
  • 1970-01-01
  • 2020-07-31
  • 2015-02-20
  • 1970-01-01
  • 1970-01-01
  • 2013-03-04
  • 2014-12-11
  • 2020-08-03
相关资源
最近更新 更多