运行它提示AttributeError: 'Paragraph' object has no attribute 'txt'是为什么
时间: 2023-06-23 20:01:36 浏览: 969
这是因为在docx的Paragraph对象中没有`txt`属性。在代码中使用`para.text`获取段落中的文本内容。所以将`para.txt`改为`para.text`即可解决问题。修改后的代码如下:
```
import docx
from PIL import Image
# 打开docx文件
doc = docx.Document('your_docx_file.docx')
# 将每个段落的文本和图片写入txt文件中
with open('your_txt_file.txt', 'w', encoding='utf-8') as f:
for para in doc.paragraphs:
f.write(para.text + '\n')
# 检查段落中是否有图片
for run in para.runs:
if run._element.tag.endswith('r'):
for elem in run._element.iter():
if elem.tag.endswith('graphic'):
for e in elem.iter():
if e.tag.endswith('blip'):
# 获取图片的文件名
img_filename = e.attrib['{http://schemas.openxmlformats.org/officeDocument/2006/relationships}link']
# 打开并保存图片
img = Image.open(img_filename)
img.save(img_filename.split('/')[-1])
# 将图片文件名写入txt文件中
f.write(img_filename.split('/')[-1] + '\n')
```
注意,您需要将`your_docx_file.docx`和`your_txt_file.txt`替换为您自己的文件名。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)