具有re和gspread的多个搜索字符串

问题描述 投票:0回答:1

我刚刚开始使用gspread,并在搜索工作表时寻找一些建议。我想搜索多个字符串并获取两个字符串都存在的特定行的结果。两个字符串必须匹配结果(逻辑AND)

搜索字符串的示例将是搜索IP地址和主机名。在工作表中,IP地址位于单元格A1中,主机名位于B1中。

我正在使用他们文档中的以下代码示例,并尝试了各种迭代,但运气不佳。

amount_re = re.compile(r'(192.168.0.1|Gi0/0.100)')
cell = worksheet.find(amount_re)

Gspread documentation

这里是数据格式:

192.168.0.1,Gi0/0.100
192.168.0.1,Gi0/0.200
192.168.0.1,Gi0/0.300
192.168.0.2,Gi0/0.100

如您所见,A和B列中有重复项,因此获得唯一结果的唯一方法是同时搜索两者。例如

192.168.0.1,Gi0/0.100

尽管它必须采用Gspread搜索格式。我不能只搜索字符串'192.168.0.1,Gi0 / 0.100'

python gspread re
1个回答
0
投票

我相信您的目标如下。

  • 您想从Google Spreadsheet中的工作表中搜索2个值,例如192.168.0.1Gi0/0.100
  • 这两个值分别对应于“ A”和“ B”列。
  • 当在同一行中找到192.168.0.1Gi0/0.100之类的2个值时,您要检索这些值。
  • 您想通过gspread和python实现此目的。
  • 您已经很讨厌使用Sheets API获取和放置Google Spreadsheet的值。

为了实现您的目标,这个答案怎么样?

[我认为很遗憾,re.compile(r'(192.168.0.1|Gi0/0.100)')无法用于实现您的目标。所以在这里,我想提出以下两种模式。

模式1:

在此模式中,使用查询语言搜索值。可以从gspread授权中使用访问令牌。

示例脚本:

searchValues = ["192.168.0.1", "Gi0/0.100"]  # Please set the search values.
spreadsheet_id = "###"  # Please set the Spreadsheet ID.
sheetName = "Sheet1"  # Please set the sheet name.

client = gspread.authorize(credentials)
ss = client.open_by_key(spreadsheet_id)
ws = ss.worksheet(sheetName)
sheet_id = ws._properties['sheetId']
access_token = client.auth.token_response['access_token']
query = "select * where A='" + \
    searchValues[0] + "' and B='" + searchValues[1] + "'"
url = 'https://docs.google.com/spreadsheets/d/' + \
    spreadsheet_id + '/gviz/tq?tqx=out:csv&gid=' + \
    str(sheet_id) + '&tq=' + urllib.parse.quote(query)
res = requests.get(url, headers={'Authorization': 'Bearer ' + access_token})
ar = [row for row in csv.reader(io.StringIO(res.text), delimiter=',')]
print(ar)
  • 在这种情况下,当找到搜索值时,ar具有搜索到的行。未找到搜索值时,ar的长度为0
  • 在这种情况下,无法检索行索引。

模式2:

在此模式下,首先,从工作表中检索所有值,然后搜索值。

示例脚本:

searchValues = ["192.168.0.1", "Gi0/0.100"]  # Please set the search values.
spreadsheet_id = "###"  # Please set the Spreadsheet ID.
sheetName = "Sheet1"  # Please set the sheet name.

client = gspread.authorize(credentials)
ss = client.open_by_key(spreadsheet_id)
ws = ss.worksheet(sheetName)
values = ws.get_all_values()
ar = [{"rowIndex": i, "value": e} for i, e in enumerate(
    values) if e[0] == searchValues[0] and e[1] == searchValues[1]]
print(ar)
  • 在这种情况下,当找到搜索值时,ar具有行索引和搜索到的行的值。未找到搜索值时,ar的长度为0
  • 在这种情况下,可以检索行索引。

参考:

© www.soinside.com 2019 - 2024. All rights reserved.