【问题标题】:Python - Mean Length Function for All Files in FolderPython - 文件夹中所有文件的平均长度函数
【发布时间】:2015-06-11 14:38:16
【问题描述】:

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

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

【问题讨论】:

  • 你似乎有一个额外的for file in files 循环,if file.endswith('.txt') 后面的那个似乎是虚假的。
  • 为什么在highest_mean函数的if之后又循环遍历所有文件?
  • 啊,我的错。但是,即使没有额外的 for 循环,该功能仍然无法工作。你还有什么看错的吗?
  • 您知道这仅对文件 names 而非内容起作用,对吧?
  • 您在发现任何大于平均值而不是最大值的文件时立即返回。而且您可能需要使用单个文件按顺序发送,例如mean_length([file]) 如果您想比较相同的事物,mean_length(file) 将始终返回 1

标签: python text directory traversal


【解决方案1】:

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

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

【讨论】:

  • 嗯,这看起来更好。谢谢。然而它只是返回''。我认为问题在于第二个函数只找到文本文件名的平均值,而不是里面的内容。声明 -- with open(string, 'r') as f: -- 已经被推荐了。
  • 您对 mean_length 的输入不应是名称序列,而是单个文件名/文件路径
  • 很抱歉一直打扰您。我已经编辑了我的初始帖子(我会改回来)以显示您推荐的更改。基本上我添加了 -- filepath = open("Desktop/Textfiles/moby.txt") -- 到最高均值函数。还是不行。
  • 不需要初始化文件路径并在for循环外打开,你试过我的解决方案,你得到了什么?
【解决方案2】:

这是一个与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))

【讨论】:

  • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 1970-01-01
  • 2020-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-07
相关资源
最近更新 更多