你不能做你想要什么 公正.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)