这条线在错误的地方分裂

The line is splitting at the wrong place

我在从“.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
"

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

试试这个:

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()

而不是 line.split(","),尝试像 line = line.split(",") 这样的东西,因为我认为 split() 函数 returns 列表,并且不会修改字符串本身。