【发布时间】:2013-07-25 16:50:39
【问题描述】:
我有一本字典。关键是动物。该值是不同动物的列表。 列表的大小和动物是什么将随着每个应用程序的使用而改变。 对于列表中的每只动物,我想在我的 BeautifulSoup 树中搜索,找到该动物的所有出现并将其包装在一个跨度标记中/用我的跨度标记的动物替换它
我无法将变量传递给 re.compile() 以帮助搜索这些动物。
我也想知道如果附近没有标签,你能否替换 BeautifulSoup 中字符串中的单个单词。
Windows 7、Python 2.7、BeautifulSoup 4 代码是这样的
for key, value in animals.iteritems(): #go through dict
if key == 'ANIMALS':
for name in value: #for name of animals in list
animal_tag = soup.new_tag("span", id=key) #create new tag with id=ANIMALS
animal_tag.string = name #create new string with name of animal
name = soup.find(text=re.compile(r'^%s$' % name))
#find animals in doc - keeps throwing a none type error
#replace animal in doc with new <span id="ANIMALS">animal>/span>
感谢任何人提供的任何帮助。
【问题讨论】:
标签: python list variables beautifulsoup