AttributeError: str has no attribute append ( web scraping , links )
AttributeError: str has no attribute append ( web scraping , links )
所以我正在做这个项目,一个小型搜索引擎。
在以下功能中,我尝试根据网站内容构建索引和数据库。 ( Index 是一个 index[word] = [url] 的字典,所以对于每个单词,它出现的 urls 的列表。而 db 是一个字典,其中 db[url] = [(title , score)] 其中对于每个 url 找到的,它的标题和一个预先给出的分数。
现在,我有 AttributeError 'str' object has no attribute 'append' in add_to_index 函数。 (我还附加了 get_content 函数,从中调用了 add_to_index。
如果有人可以帮忙,我在这里附上代码!谢谢!
def get_content( url , soup , index , db):
title = soup.title.text.strip()
head = soup.head.text.strip()
body = soup.body.text.strip()
p = soup.find_all('p')
h1 = soup.find_all('h1')
h2 = soup.find_all('h2')
h3 = soup.find_all('h3')
#Introduce all of what we have got
add_to_index( index , db, url , title , 1 )
add_to_index( index , db, url , head , 2 )
add_to_index( index , db, url , body , 3 )
add_to_index( index , db, url , p , 4 )
add_to_index( index , db, url , h1 , 4 )
add_to_index( index , db, url , h2 , 4)
add_to_index( index , db, url , h3 , 4)
def add_to_index( index , db , url , section , score ):
for word in section:
if word in index:
index[word].append(url)
else:
index[word] = ( url )
if word == title and not url in db:
db[url] = ( title , score )
创建 index[word]
初始值的这一行将其设置为字符串:
index[word] = ( url )
您应该将其设置为列表:
index[word] = [ url ]
然后你可以附加到它。
所以我正在做这个项目,一个小型搜索引擎。 在以下功能中,我尝试根据网站内容构建索引和数据库。 ( Index 是一个 index[word] = [url] 的字典,所以对于每个单词,它出现的 urls 的列表。而 db 是一个字典,其中 db[url] = [(title , score)] 其中对于每个 url 找到的,它的标题和一个预先给出的分数。
现在,我有 AttributeError 'str' object has no attribute 'append' in add_to_index 函数。 (我还附加了 get_content 函数,从中调用了 add_to_index。 如果有人可以帮忙,我在这里附上代码!谢谢!
def get_content( url , soup , index , db):
title = soup.title.text.strip()
head = soup.head.text.strip()
body = soup.body.text.strip()
p = soup.find_all('p')
h1 = soup.find_all('h1')
h2 = soup.find_all('h2')
h3 = soup.find_all('h3')
#Introduce all of what we have got
add_to_index( index , db, url , title , 1 )
add_to_index( index , db, url , head , 2 )
add_to_index( index , db, url , body , 3 )
add_to_index( index , db, url , p , 4 )
add_to_index( index , db, url , h1 , 4 )
add_to_index( index , db, url , h2 , 4)
add_to_index( index , db, url , h3 , 4)
def add_to_index( index , db , url , section , score ):
for word in section:
if word in index:
index[word].append(url)
else:
index[word] = ( url )
if word == title and not url in db:
db[url] = ( title , score )
创建 index[word]
初始值的这一行将其设置为字符串:
index[word] = ( url )
您应该将其设置为列表:
index[word] = [ url ]
然后你可以附加到它。