您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python-使用beautifulSoup查找文本,然后替换为原始汤变量

Python-使用beautifulSoup查找文本,然后替换为原始汤变量

你不能做你想要什么 公正.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)
python 2022/1/1 18:25:18 有181人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶