检查单词列表,return 从页面源代码中找到具有唯一列表的单词

Check a list of words and return found words from page source code with a unique list

我查看了其他各种问题,但 none 似乎符合要求。所以这里开始

我有一个单词列表

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。)

如果您需要额外的信息或处理(例如正则表达式/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 和正则表达式可以提供有关位置和上下文的补充信息,您可能会关心这些),那么只需定义一个自定义函数 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)