【发布时间】: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