1 回答

TA贡献1818条经验 获得超7个赞
这是一个函数,它将整个 HTML 代码和 N 作为输入,并且对于<a>元素的每次出现,创建一个元组,其中链接 URL 作为第一个元素,N 个上下文词的列表作为第二个元素。它返回列表中的元组。
def getContext(html,n):
output = []
soup = BeautifulSoup(html, 'html.parser')
for i in soup.findAll("a"):
n_side = int(n/2)
text = soup.text.replace('\n',' ')
context_before = text.split(i.text)[0]
words_before = list(filter(bool,context_before.split(" ")))
context_after = text.split(i.text)[1]
words_after = list(filter(bool,context_after.split(" ")))
if(len(words_after) >= n_side):
words_before = words_before[-n_side:]
words_after = words_after[:(n-len(words_before))]
else:
words_after = words_after[:n_side]
words_before = words_before[-(n-len(words_after)):]
output.append((i["href"], words_before + words_after))
return output
该函数使用 BeautifulSoup 解析 HTML,并找到所有<a>元素。对于每个结果,仅检索文本(使用soup.text)并去除任何换行符。然后使用链接文本将整个文本分成两部分。每一边都被解析为一个单词列表,过滤以去除任何空格,并进行切片以便最多提取 N 个上下文单词。
例如:
html = '''<html><body>
<div>This is <a href="www.example.com">a test</a>
<div>There was a big fluffy dog outside the <a href="www.petfood.com">pet food store</a> with such a sad face.<div>
</div>
</body></html>'''
print(*getContext(html,8))
输出:
('www.example.com', ['This', 'is', 'There', 'was', 'a', 'big', 'fluffy', 'dog'])
('www.petfood.com', ['fluffy', 'dog', 'outside', 'the', 'with', 'such', 'a', 'sad'])
演示:https : //repl.it/@glhr/55609756-link-context
编辑:请注意,此实现的一个缺陷是它使用链接文本作为分隔符来区分before和after。如果链接文本在 HTML 文档中在链接本身之前的某处重复,则这可能是一个问题,例如。
<div>This test is <a href="www.example.com">test</a>
一个简单的解决方法是向链接文本添加特殊字符以使其独一无二,例如:
def getContext(html,n):
output = []
soup = BeautifulSoup(html, 'html.parser')
for i in soup.findAll("a"):
i.string.replace_with(f"[[[[{i.text}]]]]")
# rest of code here
会<div>This test is <a href="www.example.com">test</a>变成<div>This test is <a href="www.example.com">[[[[test]]]]</a>.
添加回答
举报