You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从CSV读取字典列表后,如何去除答案字符串残留引号并格式化选项?

问题解决:类闪卡系统答案格式化及引号去除

背景与需求

开发类闪卡系统,限制仅使用Python基础函数与内置模块,从CSV读取字典列表数据。示例数据结构:

one_dict = [{'Question':'onevalue','Answers':['an_val','two_val','3rd_val'],'Correct Answer':'two_val'}]

核心需求:

  • 给答案选项添加序号(如[1] 'an_val' [2] 'two_val')
  • 用户输入序号后,匹配Correct Answer字段验证正确性
  • 功能函数需封装在类中,类的__init__方法暂设为pass

当前问题

编写的格式化函数运行后,答案字符串首尾残留引号。相关代码及输出如下:

def return_q(self,one_dict):
    #takes a dictionary and looks for "Question" and "Answers" as keys
    #Answers should be list so index counter puts answers list into a dictionary
    #answers = 1:option 2:option 3:option for the purposes of user input
    q_retrive = one_dict[0]['Question']
    index = 0
    answer_dict = {}
    adict = one_dict[0]['Answers']
    print(adict)
    adict = adict[1:-1].split(',')
    print(adict)
    for answer in adict:
        index +=1
        answer_dict[index] = answer
    return (q_retrive,answer_dict)

第二次print输出:

[''an_val'', 'two_val', ''3rd_val'']

返回结果示例:

('onevalue', {1: ''an_val'', 2: 'two_val', 3: ''3rd_val''})

尝试过的无效方法

  1. strip判断去除引号:未生效,因未重新赋值strip后的结果(字符串不可变,strip返回新字符串)
adict = adict[1:-1].split(',')
print(adict)
for answer in adict:
    if '"' in answer:
        answer.strip('"')  # 未保存处理后的结果
    elif "'" in adict:
        answer.strip("'")
    else:
        pass
    index +=1
    answer_dict[index] = answer
return (q_retrive,answer_dict)
  1. eval函数处理:结果不符合预期,因CSV读取的答案字符串格式导致eval后得到单个元素的列表
adict1 = one_dict[0]['Answers']
print(adict1)                       # 输出: ['1,2,3,4']
adict = eval(adict1)                # 输出: ['1,2,3,4']
print(adict1 == adict)              # 输出: False

解决方案:基础函数实现引号去除

利用字符串的strip方法一次性去除单引号、双引号及前后空格,同时修正循环中的赋值问题:

class FlashCard:
    def __init__(self):
        pass
    
    def return_q(self, one_dict):
        q_retrive = one_dict[0]['Question']
        answer_dict = {}
        # 处理从CSV读取的答案字符串(假设为类似"['an_val','two_val','3rd_val']"的格式)
        answer_str = one_dict[0]['Answers']
        # 去掉首尾方括号
        trimmed_str = answer_str[1:-1]
        # 按逗号分割成单个答案字符串
        answer_items = trimmed_str.split(',')
        # 遍历处理每个答案,去除引号和空格
        for idx, item in enumerate(answer_items, start=1):
            # strip同时去除单引号、双引号和前后空格
            cleaned_item = item.strip("'\" ")
            answer_dict[idx] = cleaned_item
        return (q_retrive, answer_dict)

验证效果

调用函数后,返回结果示例:

('onevalue', {1: 'an_val', 2: 'two_val', 3: '3rd_val'})

后续验证逻辑可通过序号获取答案,与Correct Answer字段对比:

# 示例验证
card = FlashCard()
question, answers = card.return_q(one_dict)
user_input = 2
selected_answer = answers[user_input]
if selected_answer == one_dict[0]['Correct Answer']:
    print("回答正确!")
else:
    print("回答错误!")

内容的提问来源于stack exchange,提问作者AAAddams

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 03:02:33