我刚刚开始使用gspread,并在搜索工作表时寻找一些建议。我想搜索多个字符串并获取两个字符串都存在的特定行的结果。两个字符串必须匹配结果(逻辑AND)
搜索字符串的示例将是搜索IP地址和主机名。在工作表中,IP地址位于单元格A1中,主机名位于B1中。
我正在使用他们文档中的以下代码示例,并尝试了各种迭代,但运气不佳。
amount_re = re.compile(r'(192.168.0.1|Gi0/0.100)')
cell = worksheet.find(amount_re)
这里是数据格式:
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'
我相信您的目标如下。
192.168.0.1
和Gi0/0.100
。192.168.0.1
和Gi0/0.100
之类的2个值时,您要检索这些值。为了实现您的目标,这个答案怎么样?
[我认为很遗憾,re.compile(r'(192.168.0.1|Gi0/0.100)')
无法用于实现您的目标。所以在这里,我想提出以下两种模式。
在此模式中,使用查询语言搜索值。可以从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
。在此模式下,首先,从工作表中检索所有值,然后搜索值。
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
。