如何解决检查单词列表并使用唯一列表从页面源代码返回找到的单词
我已经浏览了其他各种问题,但似乎都不符合要求。所以去了
我有一个单词列表
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_content
和l
-> 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)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。