作者Lucemia (生の直感、死の予感)
看板Python
标题Re: [问题] word count in files
时间Mon Feb 25 10:18:42 2008
※ 引述《azulazure (独在异乡为异客)》之铭言:
: I'm trying to write a command that print the largest file in the current
: working directory. I'm able to print all the files and their wordcount,
: but I don't know how to print just the largest one.
Two methods.
First, just save each file's filename and wordcount,
then use max or sort to find out the largest one.
It should looks like that ..
countcache = []
for file .. # you loop for each file
...
coundcache += [(file,wordcount)]
...
countcache.sort(key = lambda i: i[1])
print countcache[-1]
Second, use a variable to save the biggest file and wordcount
and update them with your scanning progress.
It should looks like that ..
filecache = ""
wordcountcache = -1
for file ....
if wordcount > wordcountcache:
filecache = file
wordcountcache = wordcount
print filecache, wordcountcache
btw. in fact your question is about programming,
not about python.
: Here's what I have:
: import os
: cwd = os.getcwd()
: for file in os.listdir(cwd):
: if os.path.isdir(file) == False:
: if file[0] != '.':
: word = open(file, 'r').read().split()
: wordcount = len(word)
: I tried to use range function to do the work, but it didn't work.
: I wrote like this (following what I had above):
: for x in range(wordcount):
: if x in range(wordcount - 1) == False:
: print x
: When I ran it, nothing happened. Can anyone tell me what's wrong?
: Or is there a better way to do it?
: My logic is that if the number is larger than the max number -1,
: it should be the largest number.
: Thanks in advance for any help!
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 140.110.216.36
1F:推 azulazure:thank you! I'll post my question in the programming 02/25 11:28
2F:→ azulazure:board next time~~ 02/25 11:28