Python示例函数:统计单词数量
我对Python有点生疏了,现在想找人帮我实现一个示例函数来计算单词数量(这只是一个scons脚本的示例目标,并没有做什么“真实”的事情):
def countWords(target, source, env):
if (len(target) == 1 and len(source) == 1):
fin = open(str(source[0]), 'r')
# do something with "f.read()"
fin.close()
fout = open(str(target[0]), 'w')
# fout.write(something)
fout.close()
return None
你能帮我填补一下细节吗?通常计算单词的方法是读取每一行,把它拆分成单词,然后对每一行中的每个单词在字典里增加一个计数;最后输出的时候,把单词按出现次数从高到低排序。
补充一下:我使用的是Python 2.6(确切来说是Python 2.6.5)
5 个回答
0
这里有一个很有用的例子,可以点击查看。这个例子大致上和你描述的差不多,还能计算句子的数量。
1
在不知道env
存在的原因之前,我只能这样做:
def countWords(target, source, env):
wordCount = {}
if len(target) == 1 and len(source) == 1:
with fin as open(source[0], 'r'):
for line in f
for word in line.split():
if word in wordCount.keys():
wordCount[word] += 1
else:
wordCount[word] = 0
rev = {}
for v in wordCount.values():
rev[v] = []
for w in wordCount.keys():
rev[wordCOunt[w]].append(w)
with open(target[0], 'w') as f:
for v in rev.keys():
f.write("%d: %s\n" %(v, " ".join(rev[v])))
7
在编程中,有时候我们需要处理一些数据,比如从一个地方获取数据,然后把它放到另一个地方。这个过程就像是搬家,把东西从一个房间搬到另一个房间一样。
有些时候,我们会遇到一些问题,比如数据的格式不对,或者我们想要的数据没有被正确地获取到。这就需要我们仔细检查每一步,确保每个环节都没有出错。
此外,编程中还有很多工具和库可以帮助我们更方便地处理这些数据。就像在搬家时,我们可以用箱子、手推车等工具来提高效率。
总之,处理数据的过程需要耐心和细心,确保每一步都做对了,这样才能顺利完成任务。
from collections import defaultdict
def countWords(target, source, env):
words = defaultdict(int)
if (len(target) == 1 and len(source) == 1):
with open(str(source[0]), 'r') as fin:
for line in fin:
for word in line.split():
words[word] += 1
with open(str(target[0]), 'w') as fout:
for word in sorted(words, key=words.__getitem__, reverse=True):
fout.write('%s\n' % word)
return None