如何在Python中利用Google表格搜索指定列并返回指定列问答对?
解决方案
问题分析
原代码的核心问题:
sheet.find的in_column参数不支持列表,无法直接指定多列搜索- 获取行号的方式错误,单元格对象自带
row属性,无需手动计算 - 未实现提取指定第4、5列数据的逻辑
修改后的代码
from oauth2client.service_account import ServiceAccountCredentials import gspread # 修复完整的授权scope 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("key.json", scope) client = gspread.authorize(creds) sheet = client.open("Questionnaire").sheet1 user_input = input('请输入关键词: ') # 搜索所有匹配单元格,筛选出前三列的结果 all_matches = sheet.findall(user_input) target_matches = [cell for cell in all_matches if 1 <= cell.col <= 3] if target_matches: # 取第一个匹配行的问答对(支持多匹配时可循环处理) row_num = target_matches[0].row # 直接读取第4、5列内容 question = sheet.cell(row_num, 4).value answer = sheet.cell(row_num, 5).value print(f"问题:{question}") print(f"答案:{answer}") else: print("我不知道该问题的答案")
关键修改点
- 多列搜索:先用
findall获取所有匹配单元格,再通过cell.col筛选出1-3列的目标结果 - 行号获取:直接调用单元格对象的
row属性,无需额外计算 - 指定列返回:用
sheet.cell(row_num, 列号)直接读取对应列的内容,也可改用row_values(row_num)[3:5](列表索引从0开始,对应第4、5列) - 补全了原代码中不完整的授权scope,避免授权失败
如果需要处理多个匹配结果,可以循环遍历匹配列表:
if target_matches: print(f"找到{len(target_matches)}个匹配结果:") for idx, cell in enumerate(target_matches, 1): row_num = cell.row question = sheet.cell(row_num, 4).value answer = sheet.cell(row_num, 5).value print(f"\n第{idx}个结果:") print(f"问题:{question}") print(f"答案:{answer}") else: print("我不知道该问题的答案")
内容的提问来源于stack exchange,提问作者Sophia Campione
相关产品推荐
相关产品推荐

