Python - 文件夹中所有文件的平均长度函数

Python - Mean Length Function for All Files in Folder

我有一个计算平均字符串长度的函数。现在我正在尝试编写一个函数,它将遍历并接触目录中的每个 txt 文件和 return 具有最高均值的文件。我现在所拥有的似乎无法正确遍历。请帮忙。谢谢

from __future__ import print_function
import os

def mean_length(file path):
    length = 0.0
    line_num = 0
    with open(filepath) as f:
        for line in f:
            if line.strip():
                length += len(line.strip())
                line_num += 1
    return length/line_num

def highest_mean():
    max_mean = 0 
    max_name = ""
    filepath = open("Desktop/Textfiles/moby.txt")
    for root, dirs, files in os.walk("Desktop/Textfiles"):
        for filename in files:
            if filename.endswith('.txt'):
                filepath = os.path.join(root, filename)
                if mean_length(filepath) > max_mean:
                    max_name = filename
                    max_mean = mean_length(filepath)
            return max_name

我认为您需要遍历所有文件以获得均值最高的文件,也许还有另外两个变量:

def mean_length(filepath):
    length = 0.0
    line_num = 0
    with open(filepath) as f:
        for line in f:
            if line.strip():
                length += len(line.strip())
                line_num += 1
    return length/line_num

def highest_mean():
    max_mean = 0 
    max_name = ""
    for root, dirs, files in os.walk("Desktop/Textfiles"):
        for filename in files:
            if filename.endswith('.txt'):
                filepath = os.path.join(root, filename)
                m_length = mean_length(filepath)
                if m_length > max_mean:
                    max_name = filename
                    max_mean = m_length
   return max_name

这是一个简单的代码,可以完成与 len() 内置函数相同的工作。

var =input("enter your text to calculate here : ") 

def length(var):

    count =0
    for i in var:
        count +=1
    print(count)
lent(var)

print(len(var))