18
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 的新变量,我需要在原始汤中替换它们。

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

4

1 回答 1

22

你不能用just .replace()做你想做的事。来自BeautifulSoup 文档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)

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

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

或者,如果您只需要生成的字符串(所以 Pythonstr对象,而不是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)
于 2013-02-24T21:07:57.890 回答