Python读取Word导出至Excel时遇AttributeError问题求助
解决Python读取Word内容时AttributeError: 'str' object has no attribute 'append'错误
我正在实现从Word文档读取内容并导出至Excel的功能,尝试在Python中创建列表存储读取的文本,但持续报错:AttributeError: 'str' object has no attribute 'append'。测试用Word文档结构简单,注释掉报错代码后可正常读取并打印内容,说明文件读取部分代码正常。
我的代码如下:
from docx import Document import openpyxl import pandas as pd Excel_File = "Heading and text import.xlsx" # Define some initial variables Req_Name='' Req_Text='' data = [['Req_Name', 'Req_Text']] #Create a new Excel workbook workbook = openpyxl.Workbook() #Select the default sheet (usually named 'Sheet') sheet = (workbook.active) # Open the Word document document = Document('Heading and text import.docx') # Define the function that will read in the headings from the Word document def iter_headings(paragraphs): for paragraph in paragraphs: if paragraph.style.name.startswith('Heading'): yield paragraph for heading in iter_headings(document.paragraphs): print (heading.text) #Req_Name.extend(paragraph.text) # this gives me this error --> AttributeError: 'str' object has no attribute 'extend' # OR this line of code #Req_Name.append(paragraph.text) # this gives me this error --> AttributeError: 'str' object has no attribute 'append' Req_Name # Define the function that will read in the paragraph text from the Word document def iter_text(paragraphs): for paragraph in paragraphs: if paragraph.style.name.startswith('Normal'): yield paragraph # Read in the document text for paragraph in iter_text(document.paragraphs): print (paragraph.text) # # Some clean up # workbook.save(Excel_File) # workbook.close() # # document.Close() # # word.Quit()
我尝试过使用append和extend方法,均出现如下错误:
#Req_Name.extend(paragraph.text) # this gives me this error --> AttributeError: 'str' object has no attribute 'extend' # OR this line of code #Req_Name.append(paragraph.text) # this gives me this error --> AttributeError: 'str' object has no attribute 'append'
我怀疑是列表定义有误,或者是否应该使用元组替代列表?
问题原因
你初始化Req_Name和Req_Text时用了空字符串'',而不是列表。字符串是不可变类型,没有append或extend方法,只有列表才有这些方法。
修复步骤
- 修正变量初始化:将空字符串改为空列表
Req_Name = [] Req_Text = []
- 正确添加元素到列表:在遍历标题和文本时使用
append方法
for heading in iter_headings(document.paragraphs): print(heading.text) Req_Name.append(heading.text) # 正常添加标题到列表 for paragraph in iter_text(document.paragraphs): print(paragraph.text) Req_Text.append(paragraph.text) # 正常添加文本到列表
- 写入Excel并保存:将配对后的标题和文本写入工作表,完成后保存工作簿
# 将标题和文本配对写入工作表 for name, text in zip(Req_Name, Req_Text): sheet.append([name, text]) # 保存并关闭工作簿 workbook.save(Excel_File) workbook.close()
补充说明
- 元组是不可变类型,无法动态添加元素,因此不适合用来存储读取的内容,列表才是正确选择。
- 如果Word文档中标题和普通文本数量不匹配,可根据实际逻辑调整存储方式(比如按标题分组对应文本)。
内容的提问来源于stack exchange,提问作者Tom
相关产品推荐
相关产品推荐

