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

标签 python python-2.6

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

关于python - Python 中的示例函数 : counting words,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3894265/

相关文章:

python - WTForms:FormField 的 FieldList 无法加载嵌套数据

python - 如何创建没有空白行的csv文件

python - 如何使 OS.popen 命令的输出成为选择菜单列表?

Python 2.6 到 2.5 速查表

python - 仅打印与工作日相对应的上周日期

python - 有没有办法 "nice"Python脚本的方法

python-2.6 - 如何使用命令行标志执行 python 脚本

python - pywikipedia 名称 wikiquote 未定义?

Python win32com : Excel set chart type to Line

python - 无法正确修补对象的属性