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

use*_*606 13 python beautifulsoup

commentary = soup.find('div', {'id' : 'live-text-commentary-wrapper'})
findtoure = commentary.find(text = re.compile('Gnegneri Toure Yaya')).replace('Gnegneri      Toure Yaya', 'Yaya Toure')
Run Code Online (Sandbox Code Playgroud)

评论包含需要改为Yaya Toure的Gnegneri Toure Yaya的各种情况.

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

另一个问题我是这样的代码只是发现他们并且替换它们进入一个新的变量,名为findtoure,我需要更换他们原有的汤.

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

Mar*_*ers 17

你不能做你想要什么公正 .replace().从BeautifulSoup文档NavigableString:

您无法在适当的位置编辑字符串,但可以使用,将一个字符串替换为另一个字符串replace_with().

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

findtoure = commentary.find_all(text = re.compile('Gnegneri Toure Yaya'))
for comment in findtoure:
    fixed_text = unicode(comment).replace('Gnegneri Toure Yaya', 'Yaya Toure')
    comment.replace_with(fixed_text)
Run Code Online (Sandbox Code Playgroud)

如果您想进一步使用这些评论,您需要进行新的查找:

findtoure = commentary.find(text = re.compile('Yaya Toure'))
Run Code Online (Sandbox Code Playgroud)

或者,如果你需要的只是生成的unicode文本(所以没有连接的NavigableString对象),只需收集fixed_text对象:

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

  • @blissweb:这是使用 Python 2 语法。我已经将其更新为 Python 3。 (2认同)