python - BeautifulSoup. Find and replace all instances of a word with one from my list -
i have dictionary. key animals. value list of different animals. size of list , animals change each application use. each animal in list want search through beautifulsoup tree, find occurrences of animal , wrap in span tag/replace span tagged animal
i having trouble passing variable re.compile() search these animals.
i wondering can replace single word in string in beautifulsoup if has no tags nearby.
windows 7, python 2.7, beautifulsoup 4 code someting this
for key, value in animals.iteritems(): #go through dict if key == 'animals': name in value: #for name of animals in list animal_tag = soup.new_tag("span", id=key) #create new tag id=animals animal_tag.string = name #create new string name of animal name = soup.find(text=re.compile(r'^%s$' % name)) #find animals in doc - keeps throwing none type error #replace animal in doc new <span id="animals">animal>/span>
i appreciate can give.
in case, think it's simpler manipulate raw html using string.replace()
. if text
equal raw html:
for key, value in animals.iteritems(): if key == 'animals': name in value: text.replace(name,"<span id="+key+">"+name+"</span>")
Comments
Post a Comment