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)
I'm a bit rusty in Python and am just looking for help implementing an example function to count words (this is just a sample target for a scons script that doesn't do anything "real"):
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
Could you help me fill in the details? The usual way to count words is to read each line, break up into words, and for each word in the line increment a counter in a dictionary; then for the output, sort the words by decreasing count.
edit: I'm using Python 2.6 (Python 2.6.5 to be exact)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在不知道为什么
env
存在的情况下,我只能执行以下操作:Without knowing why
env
exists, I can only do the following:此处有一个有用的示例。它的工作原理大致如您所描述的那样,并且还对句子进行计数。
There is a helpful example here. It works roughly as you describe and also counts sentences.
虽然效率不是很高,但是很简洁!
Not too efficient but it is concise!
这是我的版本:
Here my version: