2013-02-24 54 views
6
commentary = soup.find('div', {'id' : 'live-text-commentary-wrapper'}) 
findtoure = commentary.find(text = re.compile('Gnegneri Toure Yaya')).replace('Gnegneri  Toure Yaya', 'Yaya Toure') 

评论包含需要更改为Yaya Toure的Gnegneri Toure Yaya的各种实例。Python - 使用beautifulSoup查找文本,然后替换原始汤变量

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

我的另一个问题是这段代码只是找到它们并将它们替换成一个名为findtoure的新变量,我需要在原始汤中替换它们。

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

+0

@MartijnPieters我希望你晚餐有美味的汤;),但如果你不记得,我不能责怪你。 – PascalVKooten 2014-12-16 20:15:07

回答

12

你不能做你想要的与只是.replace()。从BeautifulSoup documentation on 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) 

如果你想进一步使用这些评论,你需要做一个新发现:

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

,或者,如果你所有你需要的是产生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) 
+0

感谢那个似乎已经完成了这个伎俩的人 – user2073606 2013-02-24 21:55:44