1

我有一个练习要求计算电子邮件文件中的行数和字数,不包括主题行。

我可以使用以下代码获得总行数和单词数:

file = "email.txt" 
num_lines = 0
num_words = 0
with open(file, 'r') as f:
    for line in f:
        words = line.split() 
        if not line.startswith ('Subject'):
                num_lines += 1
                num_words += len(words)
        
print(num_lines)
print(num_words)

我想定义一个函数来获取相同的信息,但是,字数统计的第二个函数不返回所需的值。

textFile = "email.txt"

def count_lines():
    with open (textFile, 'r') as file:
        num_lines = 0
        for line in file:
            words = line.split()
            if not line.startswith ('Subject'):
                num_lines = num_lines + 1
        return num_lines

def count_words():
    with open (textFile, 'r') as file:
        num_words = 0
        for words in file:
            words = line.split()
            if not line.startswith ('Subject'):
                num_words = num_words + 1
        return num_words

print(count_lines())
print(count_words())
        
4

1 回答 1

1

我建议您使用列表理解的另一种解决方案:

with open(textFile, 'r') as f:
    words_per_line = [len(line.split()) for line in f.readlines() if not line.startswith('Subject')]
    total_lines = len(words_per_line)
    total_words = sum(words_per_line)

其中words_per_line包含文件中每行的字数,因此如果计算它(len),您将获得行数,如果计算sum,您将获得总字数。

于 2020-11-14T17:12:52.457 回答