我在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
Run Code Online (Sandbox Code Playgroud)
你能帮我填写一下细节吗?计算单词的常用方法是读取每一行,分成单词,并为行中的每个单词增加字典中的计数器; 然后输出,通过减少计数对单词进行排序.
编辑:我使用的是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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5990 次 |
| 最近记录: |