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})


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部