首页 > 解决方案 > Python 3 函数多次打印同一个列表

问题描述

我需要这个函数来打印tastiera.txt文件中的句子列表

def frasi_da_file():
    arg1 = input ("percorso file: ")
    arg2 = input("codifica: ")
    if arg1 == "tastiera.txt" and arg2 == "latin1":
        f = open("tastiera.txt")
        raw = f.read()
        for line in raw: 
            q = re.split("\s+", raw)
        print (q)

现在它一遍又一遍地打印相同的列表......我认为问题出在“for”但我不知道如何解决它。

标签: pythonpython-3.xfunction

解决方案


以下是您的代码在“好 Python”中的样子:

with open("tastiera.txt") as f:
    for line in f: 
        words = re.split("\s+", line) # words, not q!
        print(words)

在这里使用正则表达式是可以的,尤其是在涉及非空白字符的情况下,但words = line.split()更合适。


推荐阅读