检查单词列表,并使用唯一列表从页面源代码中返回找到的单词



我看了其他各种问题,但似乎都不符合要求。来了

我有一个单词清单

l = ['red','green','yellow','blue','orange'] 

我在另一个变量中也有一个网页的源代码。我正在使用请求库

import requests
url = 'https://google.com'
response = requests.get(url)
source = response.content

然后我创建了一个子字符串查找函数,类似于

def find_all_substrings(string, sub):
import re
starts = [match.start() for match in re.finditer(re.escape(sub), string)]
return starts

我现在使用以下代码查找单词,我被卡住了

for word in l:
substrings = find_all_substrings(source, word)
new = []
for pos in substrings:
ok = False
if not ok:
print(word + ";")
if word not in new:
new.append(word)
print(new)
page['words'] = new

我的理想输出看起来像下面的

找到的单词-['red', 'green']

如果你只想要一个单词列表,你可以避免大部分正则表达式处理,只使用

found_words = [word for word in target_words if word in page_content]

(我已将您的string->page_contentl->target_words重命名为。(

如果您需要额外的信息或处理(例如regexs/BeautifulSoup解析器(,并且有一个需要消除重复的项目列表,您只需通过set()调用即可运行它。如果您需要一个列表而不是一个集合,或者希望保证found_words的顺序,只需再次强制转换即可。以下任何一项都可以正常工作:

found_words = set(possibly_redundant_list_of_found_words)
found_words = list(set(possibly_redundant_list_of_found_words))
found_words = sorted(set(possibly_redundant_list_of_found_words))

如果你有某种正在解析的数据结构(因为BeautifulSoup&regex可以提供关于位置和上下文的补充信息,你可能会关心这些信息(,那么只需定义一个自定义函数extract_word_from_struct(),它可以从该结构中提取单词,并在集合理解中调用它:

possibly_redundant_list_of_found_words = [extract_word_from_struct(struct) for struct in possibly_redundant_list_of_findings]
found_words = set(word for word in possibly_redundant_list_of_found_words if word in target_words)

最新更新