【问题标题】:How can I fix my code not finding keywords in a list?如何修复我的代码在列表中找不到关键字?
【发布时间】:2019-02-05 16:02:37
【问题描述】:

我有下面的代码。我需要它来从 html 页面中提取产品名称,这很好。然后,我需要它来匹配输入到列表中的一个元素并输出它的索引。即使存在诸如“Liquid Tee”之类的元素并且输入为“liquid”,它也不匹配它们。

如果您知道原因,我将不胜感激!

这是代码示例:

import urllib3
from bs4 import beautifulsoup
from lxml import etree

url = https://www.example.com    
response = http.request('GET', url)    
soup = BeautifulSoup(response.data)    
keyword = input()    
data = etree.HTML(str(soup))    
all_names = data.xpath('//a[@class="name-link"]/text()')    
namenumbered = [i for i, s in enumerate(all_names) if keyword in s]    

【问题讨论】:

  • Python 中的字符串区分大小写,因此'Liquid' 将不匹配'liquid'。至于获取列表元素的索引,可以试试idx = my_list.index('my_string')。如果my_string 不在my_list 中,index 将抛出错误。
  • @WolfgangK 谢谢 :)

标签: python-3.x beautifulsoup lxml


【解决方案1】:

如上所述,它区分大小写。如果您希望在Liquid Tee 中找到liquid,则可以使用正则表达式,或者在检查字符串中是否存在关键字时将其全部大写/全部小写:

all_names = ['liquid!', 'Liquid Tee', 'LIQUID', 'liguid ', 'hello', 'The water is LiQuId.']

keyword = 'liquid'

namenumbered = [i for i, s in enumerate(all_names) if keyword.lower() in s.lower()]

输出:

正确输出在索引/位置 0、1、2 和 5 找到的液体

print (namenumbered)
[0, 1, 2, 5]

但不更改为lower,只会识别位置[0]。

all_names = ['liquid!', 'Liquid Tee', 'LIQUID', 'liguid ', 'hello', 'The water is LiQuId.']

keyword = 'liquid'


namenumbered = [i for i, s in enumerate(all_names) if keyword in s]

输出:

print (namenumbered)
[0]

【讨论】:

    猜你喜欢
    • 2019-11-05
    • 1970-01-01
    • 2019-05-26
    • 2015-10-02
    • 2019-09-13
    • 1970-01-01
    • 2022-08-18
    • 2022-01-26
    • 2021-04-05
    相关资源
    最近更新 更多