Skip to main content
 首页 » 编程设计

python之计算文件每一行的每个单词的字符数

2025年05月04日9Terrylee

此代码将打印文本文件中的总行数、总字数和总字符数。它工作正常并提供预期的输出。但是我想计算每行中的字符数并像这样打印:-

Line No. 1 has 58 Characters 
Line No. 2 has 24 Characters 

代码:-

import string 
def fileCount(fname): 
    #counting variables 
    lineCount = 0 
    wordCount = 0 
    charCount = 0 
    words = [] 
 
    #file is opened and assigned a variable 
    infile = open(fname, 'r') 
 
    #loop that finds the number of lines in the file 
    for line in infile: 
        lineCount = lineCount + 1 
        word = line.split() 
        words = words + word 
 
    #loop that finds the number of words in the file 
    for word in words: 
        wordCount = wordCount + 1 
        #loop that finds the number of characters in the file 
        for char in word: 
            charCount = charCount + 1 
    #returns the variables so they can be called to the main function         
    return(lineCount, wordCount, charCount) 
 
def main(): 
    fname = input('Enter the name of the file to be used: ') 
    lineCount, wordCount, charCount = fileCount(fname) 
    print ("There are", lineCount, "lines in the file.") 
    print ("There are", charCount, "characters in the file.") 
    print ("There are", wordCount, "words in the file.") 
main() 

作为

for line in infile: 
    lineCount = lineCount + 1  

正在计算整行,但是如何为这个操作取每一行? 我正在使用 Python 3.X

请您参考如下方法:

将所有信息存储在字典中,然后通过 key 访问。

def fileCount(fname): 
    #counting variables 
    d = {"lines":0, "words": 0, "lengths":[]} 
    #file is opened and assigned a variable 
    with open(fname, 'r') as f: 
        for line in f: 
            # split into words 
            spl = line.split() 
            # increase count for each line 
            d["lines"] += 1 
            # add length of split list which will give total words 
            d["words"] += len(spl) 
            # get the length of each word and sum 
            d["lengths"].append(sum(len(word) for word in spl)) 
    return d 
 
def main(): 
    fname = input('Enter the name of the file to be used: ') 
    data = fileCount(fname) 
    print ("There are {lines} lines in the file.".format(**data)) 
    print ("There are {} characters in the file.".format(sum(data["lengths"]))) 
    print ("There are {words} words in the file.".format(**data)) 
    # enumerate over the lengths, outputting char count for each line 
    for ind, s in enumerate(data["lengths"], 1): 
        print("Line: {} has {} characters.".format(ind, s)) 
main() 

该代码仅适用于由空格分隔的单词,因此您需要牢记这一点。