切换Python字符串输入的好方法是什么?

2024-05-20 01:07:25 发布

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

我正在抓取一系列网页,并将其内容组织到内存中的知识库中。我需要执行不同的代码取决于我的字符串输入,这是从网站的标题爬网。你知道吗

tags = browser.find_elements_by_xpath("//div[@class='main-content-entry']/h2")
for tag in tags:
  heading = tag.get_attribute("textContent").lower().strip()
  content = tag.parent
  if heading.find("overview") != -1:
    # do this
  elif heading.find("takeaways") != -1:
    # do that
  # do more elifs
  else:
    # do something else

现在,我把它实现为if-elif-else语句。我在网站上看到过一些建议使用dicts的答案,但从我所知道的情况来看,这取决于输入是否与键完全匹配。然而,在我的例子中,由于网站所有者的不一致性,精确匹配并不总是可能的。你知道吗

这些页面的结构足以让我知道标题名称是什么,所以我可以在代码中提前定义“键”。然而,在一些标题的百余页中,有些是打字错误和轻微的变体。例如:

  • 费用和资金
  • 费用
  • 费用和资金
  • 证书
  • 证书
  • 证书和考试
  • 考试和证书

我能做的最好的事情,就像我现在所做的那样,就是首先扫描页面,确定整个标题集,然后手动定义子字符串,在我的代码中使用,这样可以避免重复。你知道吗

考虑到上述情况,有没有更好的方法来迭代执行链接的if else语句?你知道吗

编辑

Replacements for switch statement in Python?中建议的答案在我的情况下不起作用。举个例子:

def do_this(heading):
  return {
    "overview": do_overview(),
    "fees": do_fees(),
    # ...
  }[heading]

这将是该问题答案所建议的实施办法。但是当heading"fees & funding""fees""fees &funding"等等时,我怎么返回do_fees()。?如果键值是heading的子字符串,则需要执行正确的函数。你知道吗


Tags: 字符串答案代码标题if网站tagoverview
2条回答

Considering the above, is there a better way then to iteratively execute a chained if-elif-else statement?

您不需要使用特定键直接从字典中查找值。您可以使用字典来压缩解析逻辑:

def extract_overview(content):
    ...

def extract_takeaways(content):
    ...

EXTRACTORS = {
    'overview': extract_overview,
    'takeaways': extract_takeaways,
    ...
}

for tag in tags:
    heading = tag.get_attribute("textContent").lower().strip()
    content = tag.parent

    for substring, function in EXTRACTORS.items():
        if substring in heading:
            result = function(content)
            break
    else:
        # No extractor was found

如果您想匹配键入的字符串,那么您将需要对一些输入进行某种模糊匹配。但是对于那些格式良好的语句,可以通过调整dictionary方法来获得switch语句的线性时间优势。(这只在你有很多案子的时候才重要)。你知道吗

funcs = {
    "certificates": lambda: "certificates",
    "fees": lambda: "fees",
}

headings =['Fees & Funding', 'Fees', 'Fees &Funding', 'Certificates',
           'Certificate', 'Certificat & Exams', 'Exams & Certificates']

def do_this(heading):
    words = heading.lower().split()
    funcs_to_call = [funcs[word] for word in words if word in funcs]
    if len(funcs_to_call) == 1:
        return funcs_to_call[0]()
    elif len(funcs_to_call) == 0:
        return 'needs fuzzy matching'
    else:
        #alternatively treat it as being in multiple categories.
        raise ValueError("This fits more than one category")


for heading in headings:
    print(heading, parse(heading), sep = ': ')
#outputs:
Fees & Funding: fees
Fees: fees
Fees &Funding: fees
Certificates: certificates
Certificate: needs fuzzy matching
Certificat & Exams: needs fuzzy matching
Exams & Certificates: certificates

如果你能够预测你将要面对的打字错误的种类,你可以提前清理字符串以获得更精确的匹配,比如删除符号和使单词复数。你知道吗

相关问题 更多 >