定义一个函数来读取文件并计算每行中的单词数

Defining a function to read from a file and count the number of words in each line

我是 python 的新手。我正在尝试定义一个函数来从给定文件中读取并计算每行中的单词数并将结果输出为列表。

这是我的代码:

def nWs(filename):

with open(filename,'r') as f:
    k=[]
    for line in f:
        num_words=0
        words=line.split()
        num_words +=len(words)
        k.append(num_words)
    print (k)
print( nWs('random_file.txt') )

预期输出类似于:

[1, 22, 15, 10, 11, 13, 10, 10, 6, 0]

但是 returns:

[1, 22, 15, 10, 11, 13, 10, 10, 6, 0]
None

我不明白为什么要返回 None 这个词。文本文件没有任何问题,它只是随机文本,我只是想在 1 个文件中打印单词。所以我不明白这个结果。谁能解释为什么?还有我怎样才能摆脱这个 None 术语。

我假设当您尝试 运行 时缩进是正确的,否则它不会 运行。

None是你在打印语句中调用函数的结果。因为 nWs 没有 return 任何东西,打印语句打印 None。您可以在不使用 print 语句的情况下调用该函数,或者不在函数中使用 print,而是使用 return 然后 print.

def nWs(filename):

    with open(filename,'r') as f:
        k=[]
        for line in f:
            num_words=0
            words=line.split()
            num_words +=len(words)
            k.append(num_words)
        print (k)

nWs('random_file.txt')

def nWs(filename):

    with open(filename,'r') as f:
        k=[]
        for line in f:
            num_words=0
            words=line.split()
            num_words +=len(words)
            k.append(num_words)
        return k

print(nWs('random_file.txt'))