问题描述
我正在尝试编写一个脚本,该脚本采用包含 X 个 .odt 文件的文件夹并计算字数。它必须将它写在一个带有日期的 csv 文件中。
我尝试使用 odfpy 来做到这一点。
import odf
import glob
import pandas as pd
import os
from odf.opendocument import load as load_odt
filenames = []
word_counts = []
for f in glob.glob('*.odt'):
print(f)
doc = load_odt(f)
if doc.text.hasChildNodes():
n = 0
for e in doc.text.childNodes:
if ":text:" in e.qname[0]:
words = [w for w in str(e).split(" ") if len(w) > 0]
n += len(words)
else:
print(e.qname[0])
filenames.append(f)
word_counts.append(n)
df = pd.DataFrame({'date':[pd.Timestamp.Now() for i in range(len(filenames))],'filename':filenames,'word_count':word_counts})
print(df)
csv_filename = 'word_count.csv'
它以某种方式工作,但 CSV 中缺少一些文件。有什么想法吗?
解决方法
看起来像这样:
import odf
import glob
import pandas as pd
import os
from odf.opendocument import load as load_odt
filenames = []
word_counts = []
for f in glob.glob('*.odt'):
print(f)
doc = load_odt(f)
n = 0
for e in doc.body.childNodes:
if type(e) == odf.element.Text or type(e) == odf.element.Element:
words = [w for w in str(e).split(" ") if len(w) > 0]
n += len(words)
else:
print(type(e))
filenames.append(f)
word_counts.append(n)
df = pd.DataFrame({'date':[pd.Timestamp.now() for i in range(len(filenames))],'filename':filenames,'word_count':word_counts})
print(df)
csv_filename = 'word_count.csv'
df.to_csv(csv_filename,index = False,mode='a',header=not os.path.exists(csv_filename))
print(df.sum(axis = 0))
它的字数与 LibreOffice 的字数不完全相同,但足够了。