猿问

线路在错误的地方分裂

我在从“.txt”文件中拆分行时遇到问题。


我希望该行在','.split() 函数具有参数时拆分每个字符。


有人可以告诉我我做错了什么以及如何解决甚至改进它。


那将不胜感激


在我将 split() 函数移动到 FOR 循环之前,该行在正确的位置拆分,但是即使我输入了正确的答案,它也不会将其识别为正确的答案,我尝试将答案变成一个字符串检查,但它没有影响问题。


Python


def 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 chabolas

Managers,Los gerentes

Running water,El agua corriente

"

预期的结果应该允许我输入另一侧的内容','并说它是正确的


Smart猫小萌
浏览 152回答 2
2回答

aluckdog

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

江户川乱折腾

试试这个: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()
随时随地看视频慕课网APP

相关分类

Python
我要回答