python替换文件中的变量_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')

Commentary contains various instances of Gnegneri Toure Yaya that need changing to Yaya Toure.

findAll() doesn't work as findtoure is a list.

The other problem I have is this code simply finds them and replaces them into a new variable called findtoure, I need to replace them in the original soup.

I think I am just looking at this from the wrong perspective.

解决方案

You cannot do what you want with just .replace(). From the BeautifulSoup documentation on NavigableString:

You can’t edit a string in place, but you can replace one string with another, using replace_with().

That's exactly what you need to do; take each match, then call .replace() on the contained text and replace the original with that:

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)

If you want to use these comments further, you'll need to do a new find:

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

or, if you all you need is the resulting strings (so Python str objects, not NavigableString objects still connected to the BeautifulSoup object), just collect the fixed_text objects:

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值