繁体   English   中英

使用python打印字符串列表中项目位置的最佳方法是什么

[英]What is the best way to print position of items in the list of strings using python

我已经开始了一些网络抓取工作,而且我对 python 还很陌生。 我想在python的字符串列表中找到元素的位置。 到目前为止,我已经尝试了一些语句,但 python 总是返回“bool is not iterable”。 我正在使用正则表达式,并且我已经设法获得了有价值的东西,现在想要在列表中显示匹配字符串的位置。 当我使用下面的代码时,我得到这样的输出:

for i in range(0, len(string_data)):
print(string_data[i])

<td class="kx o_1" data-bookmaker="16">
<td class="kx o_0" data-bookmaker="16">
<td class="kx o_2 winner" data-bookmaker="16">

在列表中找到匹配单词“winner”的项目位置的最佳方法是什么。在我的情况下,如果我从 0 开始计算它,它将是第二个位置,但我该怎么做?

可能有一种更简洁、更短的方法来做到这一点,但我们可以写出一个很好的循环来跟踪元素位置,搜索td元素列表,一旦遇到winner ,就打印出该位置:

position = 0 # start position at index 0

td_elements = driver.find_elements_by_tag_name("td") # get elements to iterate
# td_elements = driver.find_elements_by_xpath("//td[contains(@class, 'kx')]")
# ^ this is an alternate selector, in case tag_name is too generic.

# iterate td elements, searching for 'winner' in the class
for element in td_elements:

    # check if class attribute contains winner
    if ("winner" in element.get_attribute("class")):
        print(str(position) # winner! print position of element

    else: position++ # increment position if we did not find a winner

希望这个对你有帮助。 另一个用户使用BeautifulSoup发布了一个解决方案,如果您已经在使用 BS,它似乎工作得很好。 我提供了一个纯 Selenium 示例,以防您在这里使用。

你可以用np.where做到这np.where

如果您的列表包含您想要匹配的确切字符串,例如:

import numpy as np
items = ['something', 'something else', 'winner']
winner_ids = np.where([item == 'winner' for item in items])

你提到了re所以这里是你如何匹配子字符串:

import numpy as np
items = ['something', 'something else', 'something containing winner']
winner_ids = np.where([re.findall('winner', item) for item in items])

请注意np.where将返回项目列表。 在这两个示例中, winner_ids(array([2]),) 如果您希望找到一个获胜者,则可以执行以下操作:

winner_id = winner_ids[0][0]

现在winner_id2正如你所期望的。

您可以使用enumerate返回索引值:

from bs4 import BeautifulSoup

html = '''
<td class="kx o_1" data-bookmaker="16">
<td class="kx o_0" data-bookmaker="16">
<td class="kx o_2 winner" data-bookmaker="16">'''

soup = BeautifulSoup(html, 'html.parser')
for idx, item in enumerate(soup.find_all('td')):
    print (idx, item['class'])

输出:

0 ['kx', 'o_1']
1 ['kx', 'o_0']
2 ['kx', 'o_2', 'winner']

如果有赢家,就返回:

for idx, item in enumerate(soup.find_all('td')):
    if 'winner' in item['class']:
        print (idx, item['class'])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM