Python如何搜索字典键以查看是否包含特定字符串

2024-06-13 09:22:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经尽力了,如果我不知道该怎么说。在

我正在用feedparser解析RSS提要。在

根据文档,我能够将我的结果解析为指向某个漏洞的链接+它的RSS帖子标题。在

这是我的代码:

import feedparser

# product variables
ie = ['Internet Explorer', 'IE', 'Explorer', 'Internet_Explorer']
nix = ['Linux', 'SUSE', 'Red Hat', 'RHEL', 'Ubuntu', 'Debian_Linux']
win = ['Windows_']

# NVD RSS feed variable
d = feedparser.parse('https://nvd.nist.gov/feeds/xml/cve/misc/nvd-rss-  analyzed.xml')
print("================================")
print(d['feed']['title'])
print("================================")

for entry in d.entries:
    print(entry.title, entry.link)

这将返回如下结果:

^{pr2}$

我还尝试分析原始数据,即:

for entry in d.entries:
    print(entry)

现在这向我展示了title是字典中的一个键(我想),它的值是CVE-2018-8132 (windows_10, windows_server_2016)

我想做的是一个if语句,它可能是这样的:如果titlevalue包含一个单词(从列表的顶部),然后做一些事情

我在feedparser的文档中找不到如何做到这一点。我真的很感激你的帮助。在

编辑(2018-06-15):

我想出来了。在

这是我为将来寻找它的人准备的代码:

# library imports
import feedparser
import re
import smtplib
import datetime
import time

# NVD RSS feed variable
d = feedparser.parse('https://nvd.nist.gov/feeds/xml/cve/misc/nvd-rss-  analyzed.xml')
print("\n+++++++++++++++++++++++++++++++++++++++")
print(d['feed']['title'], 'Scanner')
print("+++++++++++++++++++++++++++++++++++++++\n")


# function for iterating through the entries and printing out how many vulns there are
def product_scan(product_name):

    # vulnerability links list
    vuln_list = []

    # counter for how many vulns per product
    count = 0
    for entry in d.entries:
        if product_name in entry.title:
            count += 1
            # here we append the hyperlinks of the CVEs to a pre-defined list so we can manipulate it later
            vuln_list.append(entry.link)


    # making it look nice
    if count == 1:
 print('===============================================================\nThere is', count, product_name,
          'related vulnerability:')
    elif count == 0:
        print('')
    else:
      print('===============================================================\nThere are', count, product_name,
          'related vulnerabilities:')

    # this for loop is for enumerating the links for each product CVE code
    for x in vuln_list:
    print(x)


# calling the function and searching for vulns based on keyword(s)
product_list = ['mysql', 'windows', 'linux', 'explorer', 'php', 'webex', 'firefox', 'norton', 'mcafee', 'symantec']
for product in product_list:
    product_scan(product)

Tags: theinimportfortitlefeedcountxml
1条回答
网友
1楼 · 发布于 2024-06-13 09:22:06

Geronimo,如果您只想检查字典中是否有一个键,那么可以使用in关键字

d = {'abc':'123','bbg':'456','tig':'567'}
if 'abc' in d:
   print("key is in here")

如果您想对过滤后的键和值执行更多操作,可以使用dictionary comprehension(类似于list comprehension,但用于dicts)Filter dict to contain only certain keys?

相关问题 更多 >