首页 > 解决方案 > AttributeError: 'str' object has no attribute 'P' 当尝试从所有 .odt 文件中递归提取文本时,使用 odfpy 库

问题描述

我编写了一个脚本,以递归方式将我的所有 .odt 文件(位于 CWD 和所有子目录中)转换为文本文件。有问题的代码:

import glob, os
from odf import text, teletype
from odf.opendocument import load

fileList = glob.glob(f"{os.getcwd()}/**/*.odt", recursive=True) 

for f in fileList:
    textdoc = load(f)
    allparas = textdoc.getElementsByType(text.P) 
    print(allparas)
    s = len(allparas)
    text = ""
    for i in range(s):
        text += teletype.extractText(allparas[i])
        text += "\n"

    output_file = f.replace(".odt", "")
    with open(output_file, 'w') as textfile:
        textfile.write(text)

当我运行它时,我收到以下错误:

文件“./odtR.py”,第 12 行,在 allparas = textdoc.getElementsByType(text.P) AttributeError: 'str' object has no attribute 'P'

相比之下,当我运行一个类似的脚本时,一切都很好,该脚本旨在仅转换我从 CWD 选择的一个文件。这是此脚本的代码:

from odf import text, teletype
from odf.opendocument import load

path_to_your_odt_file = input("What is the name of your odt file?\n")


output_file = path_to_your_odt_file.replace(".odt", "")


textdoc = load(path_to_your_odt_file)
allparas = textdoc.getElementsByType(text.P) 
s = len(allparas)
text = ""
for i in range(s):
    text += teletype.extractText(allparas[i])
    text += "\n"
    
output_file = path_to_your_odt_file.replace(".odt", "")
with open(output_file, 'w') as textfile:
    textfile.write(text)

我在以前的剧本中做错了什么?你会如何重写它?

标签: pythonglobtext-extractionodfodfpy

解决方案


推荐阅读