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
您可以為每個(gè)文件創(chuàng)建一個(gè)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})
總結(jié)
以上是生活随笔為你收集整理的python创建多个txt文件-python-在目录中创建多个文本文件的字数字...的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: tipi 深入理解php内核 pdf_大
- 下一篇: pdf批量添加图章_给PDF批量添加文本