简体   繁体   中英

Python - Mean Length Function for All Files in Folder

I have a function that finds the mean string length. Now I'm trying to write a function that will traverse and touch every txt file in the directory and return the file with the highest mean. What I've got right now doesn't seem to traverse properly. Pleeease help. Thanks.

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

I think you need to go through all files to get the one with the highest mean, maybe with another two variables:

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

#and this is a simple code do the same work of len() built in function.

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM