你不能用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)