为了账号安全,请及时绑定邮箱和手机立即绑定

线路在错误的地方分裂

线路在错误的地方分裂

Smart猫小萌 2022-06-02 18:15:29
我在从“.txt”文件中拆分行时遇到问题。我希望该行在','.split() 函数具有参数时拆分每个字符。有人可以告诉我我做错了什么以及如何解决甚至改进它。那将不胜感激在我将 split() 函数移动到 FOR 循环之前,该行在正确的位置拆分,但是即使我输入了正确的答案,它也不会将其识别为正确的答案,我尝试将答案变成一个字符串检查,但它没有影响问题。Pythondef main():  file = open ("Spanish Words Randomized.txt", "r")  line = file.readline()  for line in file:    line.split(",")    answer = input("What is '" + line[0] + "' in Spanish?:")    if answer == str(line[1]):       print("correct")    elif answer != str(line[1]):        print("It was",line[1])main()这些是 .txt 文件的前 3 行"A shanty town,Un barrio de chabolasManagers,Los gerentesRunning water,El agua corriente"预期的结果应该允许我输入另一侧的内容','并说它是正确的
查看完整描述

2 回答

?
aluckdog

TA贡献1847条经验 获得超7个赞

而不是line.split(","),尝试类似的东西line = line.split(","),因为我认为该split()函数返回列表,并且不会修改字符串本身。



查看完整回答
反对 回复 2022-06-02
?
江户川乱折腾

TA贡献1851条经验 获得超5个赞

试试这个:


def main():


    with open ("Spanish Words Randomized.txt", "r") as fin :

        # read the whole file, stripping EOL and filtering the empty lines

        text = [line.strip() for line in fin.readlines() if len(line) > 1]


    for line in text :

       q, a = line.split(",")    # need to catch the results of the split()

       answer = input("What is '" + q + "' in Spanish?:")

       if answer == a :

           print("correct")

       else :    # no point to check what we already know

           print("It was", a)


main()


查看完整回答
反对 回复 2022-06-02
  • 2 回答
  • 0 关注
  • 150 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号