【问题标题】:How to count words in a Libre Office file using a script?如何使用脚本计算 Libre Office 文件中的单词?
【发布时间】:2021-07-23 21:21:04
【问题描述】:

我正在尝试编写一个脚本,该脚本需要一个包含 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 中有一些文件丢失。有什么想法吗?

【问题讨论】:

    标签: python libreoffice odf odfpy


    【解决方案1】:

    看起来这样可行:

    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 不完全相同,但已经足够了。

    【讨论】:

    • 字数不完全一样 好吧,不如问问DocumentInfo.DocumentStatistic
    • 我该怎么做?
    猜你喜欢
    • 1970-01-01
    • 2013-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多