【问题标题】:Check a list of words and return found words from page source code with a unique list检查单词列表并使用唯一列表从页面源代码返回找到的单词
【发布时间】:2020-09-24 12:24:00
【问题描述】:

我查看了其他各种问题,但似乎没有一个符合要求。就这样吧

我有一个单词列表

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']

【问题讨论】:

  • 你试过 BeautifulSoup 解析器吗?
  • 嘿@woblob,与其说是解析器,不如说是逻辑。该函数确实找到了这个词。它的列表输出有时会翻倍,有时会出现 10 次。
  • 你不要改变“ok”变量
  • “我被卡住了”没有帮助。执行代码时遇到什么错误。哪一行导致错误?

标签: python python-3.x list python-requests python-re


【解决方案1】:

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

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)

【讨论】:

  • 啊!如此简单,但我花了几个小时尝试调试,因为我的列表不断被覆盖。谢谢你好心的陌生人。
猜你喜欢
  • 2016-06-27
  • 1970-01-01
  • 1970-01-01
  • 2022-01-13
  • 2013-10-21
  • 1970-01-01
  • 2018-12-27
  • 2018-10-13
  • 2021-12-14
相关资源
最近更新 更多