300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > python在当前目录创建txt文件-python-在目录中创建多个文本文件的字数字...

python在当前目录创建txt文件-python-在目录中创建多个文本文件的字数字...

时间:2018-12-01 10:15:41

相关推荐

python在当前目录创建txt文件-python-在目录中创建多个文本文件的字数字...

使用collections.Counter.

示例文件:

/tmp/foo.txt

hello world

hello world

foo bar

foo bar baz

/tmp/bar.txt

hello world

hello world

foo bar

foo bar baz

foo foo foo

您可以为每个文件创建一个Counter,然后将它们加在一起!

from collections import Counter

def word_count(filename):

with open(filename, 'r') as f:

c = Counter()

for line in f:

c.update(line.strip().split(' '))

return c

files = ['/tmp/foo.txt', '/tmp/bar.txt']

counters = [word_count(filename) for filename in files]

# counters content (example):

# [Counter({'world': 2, 'foo': 2, 'bar': 2, 'hello': 2, 'baz': 1}),

# Counter({'foo': 5, 'world': 2, 'bar': 2, 'hello': 2, 'baz': 1})]

# Add all the word counts together:

total = sum(counters, Counter()) # sum needs an empty counter to start with

# total content (example):

# Counter({'foo': 7, 'world': 4, 'bar': 4, 'hello': 4, 'baz': 2})

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。