Python 属性错误:';str';对象没有属性';P';尝试使用odfpy库从所有.odt文件中递归提取文本时
我编写了一个脚本,以递归方式将CWD和所有子目录中的所有.odt文件转换为文本文件。有关守则:Python 属性错误:';str';对象没有属性';P';尝试使用odfpy库从所有.odt文件中递归提取文本时,python,glob,text-extraction,odf,odfpy,Python,Glob,Text Extraction,Odf,Odfpy,我编写了一个脚本,以递归方式将CWD和所有子目录中的所有.odt文件转换为文本文件。有关守则: 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)
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”对象没有属性“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)
前一个剧本我做错了什么?如何重写它?行
text=”“
将text
转换为str
,而不是顶部的导入。只需使用不同的变量名,例如txt=”“
等@quamrana谢谢,我这么做了,效果很好。但我无法理解这一点——为什么在第二个脚本中,相同的变量文本不是导致相同问题的原因。这是因为您先使用“text.P”,然后再修改文本。(您的第一个脚本有一个循环,在该循环中,您可以在更改后再次使用“text.P”)