Python (Google Sheets API) - 搜索某个字符串并返回整行

Python (Google Sheets API) - Searching for a certain string and returning the whole row

所以现在我有一个电子表格,其中包含我的 discord 服务器中被禁止的玩家列表。现在我正在尝试创建一个 python 脚本,允许您输入 string/int,如果它找到匹配项,它 return 整行。

电子表格示例:(会有更多列,因为这只是一个示例)

https://gyazo.com/82aee173103cbb77cff067a9e28c5fc1

如您所见,如果用户提供了不和谐 ID,它应该 return 值所在的整行。

到目前为止我的设置:

import gspread
from oauth2client.service_account import ServiceAccountCredentials

scope = ["https://spreadsheets.google.com/feeds",'https://www.googleapis.com/auth/spreadsheets',"https://www.googleapis.com/auth/drive.file","https://www.googleapis.com/auth/drive"]

creds = ServiceAccountCredentials.from_json_keyfile_name("creds.json", scope)

client = gspread.authorize(creds)

sheet = client.open("MRP Blacklist Data").sheet1

values = result.get('values', [])

    if not values:
        print('No data found.')
    else:
        print('Name, Major:')
        for row in values:
            print('%s, %s' % (row[0], row[4]))

代码不完整,我不知道如何完成它。任何提示或建议都会有很大帮助!

您可以使用 gspread .find("string").row_values(n) 函数。

.find("string") - 获取与字符串匹配的单元格的位置。它具有 .row 和 .cell 属性,您可以使用它们来定位单元格。

row_values(n) - 获取给定行号的所有值:

在您的代码中:

import gspread
from oauth2client.service_account import ServiceAccountCredentials

scope = ["https://spreadsheets.google.com/feeds",'https://www.googleapis.com/auth/spreadsheets',"https://www.googleapis.com/auth/drive.file","https://www.googleapis.com/auth/drive"]
creds = ServiceAccountCredentials.from_json_keyfile_name("creds.json", scope)
client = gspread.authorize(creds)
sheet = client.open("MRP Blacklist Data").sheet1

print(sheet.row_values(sheet.find("ABC").row))

它将打印如下内容:

['Test1', 'TestID1', 'ABC', 'Costal Craft', 'None', 'Just Because']

这是我的示例数据:

注意:.find() 只会 return 第一次出现的字符串,如果要搜索所有出现的地方,请使用 .findall() 循环遍历列表并使用 row_values 到每个元素。

.findall() 示例:

import gspread
from oauth2client.service_account import ServiceAccountCredentials

scope = ["https://spreadsheets.google.com/feeds",'https://www.googleapis.com/auth/spreadsheets',"https://www.googleapis.com/auth/drive.file","https://www.googleapis.com/auth/drive"]
creds = ServiceAccountCredentials.from_json_keyfile_name("creds.json", scope)
client = gspread.authorize(creds)
sheet = client.open("MRP Blacklist Data").sheet1
values = sh.findall("ABC")
for r in values:
    print(', '.join(sh.row_values(r.row)))

输出应如下所示:

Test1, TestID1, ABC, Costal Craft, None, Just Because
Test3, TestID3, ABC, Costal Craft, None, None

测试数据:

参考:

Finding a cell