Skip to main content
 首页 » 编程设计

python之Python 中的示例函数 : counting words

2025年05月04日13lvdongjie

我对 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)

请您参考如下方法:

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