Re: [問題] word count in files
※ 引述《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
推
02/25 11:28, , 1F
02/25 11:28, 1F
→
02/25 11:28, , 2F
02/25 11:28, 2F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 3 之 3 篇):
Python 近期熱門文章
PTT數位生活區 即時熱門文章