繁体   English   中英

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

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

所以现在我有一个电子表格,其中包含来自我的 discord 服务器的被禁止玩家列表。 现在我正在尝试创建一个 python 脚本,该脚本允许您输入字符串/整数,如果找到匹配项,则返回整行。

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

https://gyazo.com/82aee173103cbb77cff067a9e28c5fc1

如您所见,如果用户给出 discord ID,它应该返回值所在的整行。

到目前为止我的设置:

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) function。

.find("string") - 获取与字符串匹配的单元格的 position。 它具有 .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() 只会返回第一次出现的字符串,如果你想搜索所有出现的地方,use.findall() all 循环遍历列表并对每个元素使用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)))

Output 应如下所示:

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

测试数据: 在此处输入图像描述

参考:

寻找细胞

暂无
暂无

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

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