기사 디렉토리
1. Python에서 라이브러리를 설치하고 제거하는 방법
1.1 설치
검색창에서 검색한 cmd
다음 pip install
+ 를 입력합니다 库名字
. 예를 들어 python-pptx를 설치해야 하는 경우 를 입력합니다 pip install python-docx
.
1.2 제거
검색창에서 검색한 cmd
다음 pip uninstall
+ 를 입력합니다 库名字
. 예를 들어 python-pptx를 제거해야 하는 경우 를 입력합니다 pip uninstall python-docx
.
2. 도구
제가 사용하는 것은 pycharm
, 개인적으로 사용감이 더 좋습니다.
구성 자습서를 다운로드하려면 여기를 클릭하십시오.
3. PPT 콘텐츠를 Word로 변환
3.1 PPT 텍스트 상자의 텍스트를 Word로 변환
3.1.1 필수 라이브러리
다운로드해야 하는 라이브러리는 다음 python-pptx
과 같습니다 python-docx
.
3.1.2 구현 코드
from pptx import Presentation
from docx import Document
wordfile = Document()
# 给定ppt文件所在的路径
filepath = r'E:\vs\w.pptx'
pptx = Presentation(filepath)
# 遍历ppt文件的所有幻灯片页
for slide in pptx.slides:
# 遍历幻灯片页的所有形状
for shape in slide.shapes:
# 判断形状是否含有文本框,如果含有则顺序运行代码
if shape.has_text_frame:
# 获取文本框
text_frame = shape.text_frame
# 遍历文本框中的所有段落
for paragraph in text_frame.paragraphs:
# 将文本框中的段落文字写入word中
wordfile.add_paragraph(paragraph.text)
#word文档存放的路径
save_path = r'E:\vs\w.docx'
wordfile.save(save_path)
3.1.3 구체적인 설명
구체적인 설명은 여기나
여기를
클릭 하세요 주의할 점은 Document 내부의 * 뒤에 있는 *를 제거해야 하며, 그렇지 않으면 오류가 보고되며 wordfile.add_paragraph(paragraph.text
이 문장에는 해당 내용이 부족 합니다 )
.
3.2 PPT 사진도 내보내기
3.2.1 필수 라이브러리
다운로드해야 하는 라이브러리는 다음과 같습니다. python-pptx
.
3.2.2 구현 코드
사진이 있으면 현재 Pycharm 프로젝트 폴더에 바로 저장됩니다.
from pptx import Presentation
from pptx.shapes.picture import Picture
prs = Presentation("E:\k\w.pptx")#这是你ppt的路径
index = 1
#读取幻灯片的每一页
for slide in prs.slides:
# 读取每一板块
for shape in slide.shapes:
# print(dir(shape))
#是否有文字框
if shape.has_text_frame:
#读文字框的每一段落
for paragraph in shape.text_frame.paragraphs:
if paragraph.text:
# 输出段落文字,也有一些属性,可以用dir查看
# print(dir(paragraph))
print(paragraph.text)
#是否有表格
elif shape.has_table:
one_table_data = []
for row in shape.table.rows: # 读每行
row_data = []
for cell in row.cells: # 读一行中的所有单元格
c = cell.text
row_data.append(c)
one_table_data.append(row_data) # 把每一行存入表
#用二维列表输出表格行和列的数据
print(one_table_data)
# 是否有图片
elif isinstance(shape, Picture):
#shape.image.blob:二进制图像字节流,写入图像文件
with open(f'{
index}.jpg', 'wb') as f:
f.write(shape.image.blob)
index += 1
4. OCR을 사용하여 이미지 정보를 Word에 저장
4.1 바이두 API 사용
4.1.1 필수 라이브러리
다운로드해야 하는 라이브러리는 다음 baidu-aip
과 같습니다 python-docx
.
4.1.2 구현 코드
# 从相应的aip导入AipOcr模块
from aip import AipOcr
from docx import Document
wordfile = Document()
# 输入凭证
APP_ID = "19307867"
API_Key = "HM1UDlzRPrr7TE6xw9YHDSnZ"
Secret_Key = "6jUGVGRLMrbByWz0vPs5w5NOS8m6GMOl"
aipOcr = AipOcr(APP_ID, API_Key, Secret_Key)
# 输入资源
filePath = r"D:\pythonProject"
for i in range(1, 499):
filePath1 = filePath + "\\" + str(i) + ".jpg" # 最好是jpg,名称统一
image = open(filePath1, "rb").read()
# 接通ocr接口
result = aipOcr.basicGeneral(image)
# 输出
mywords = result["words_result"]
for i in range(len(mywords)):
print(mywords[i]["words"])
wordfile.add_paragraph(mywords[i]["words"])
save_path = r'E:\vs\w.docx'
wordfile.save(save_path)
4.1.3 구체적인 설명
4.1.4 기존 문제
api를 직접 호출하는 방식으로, 여러 번 호출하면 무효가 되며, 다시 호출하려면 시간이 좀 걸립니다. 따라서 많은 인식이 필요한 경우에는 이 방법을 권장하지 않습니다.
4.2 tesseract 기반 OCR 인식
4.2.1 필수 라이브러리 및 소프트웨어
다운로드해야 하는 라이브러리는 python-pptx
, pytesseract
및 입니다 pillow
.
다운로드해야 하는 소프트웨어 tesseract
는 다른 블로거를 참조하는 특정 설치 및 구성 방법입니다.
4.2.2 구현 코드
from PIL import Image
import pytesseract
import pptx
image = Image.open(r'2.jpg')#打开图片
result = pytesseract.image_to_string(image,lang='eng')#使用简体中文字库识别图片并返回结果
print(result)#打印识别的图片内容
4.2.3 구체적인 설명
Python3은 이미지 인식을 위해 pytesseract를 사용합니다.Python3.6은
이미지 변환을 실현합니다.
4.2.4 기존 문제
이 방법의 인식률은 사진의 양수와 음수를 잘 인식하지 못하기 때문에 제 요구 사항을 충족하지 못합니다.
4.3 몇 가지 추가 방법
4.3.1 설치할 라이브러리
다운로드해야 하는 라이브러리는 requests
및 python-docx
(워드로 변환하는 데 필요)입니다.
4.3.2 구현 코드
import requests
import base64
from docx import Document
wordfile = Document()
def ocr(img_path: str) -> list:
'''
根据图片路径,将图片转为文字,返回识别到的字符串列表
'''
# 请求头
headers = {
'Host': 'cloud.baidu.com',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36 Edg/89.0.774.76',
'Accept': '*/*',
'Origin': 'https://cloud.baidu.com',
'Sec-Fetch-Site': 'same-origin',
'Sec-Fetch-Mode': 'cors',
'Sec-Fetch-Dest': 'empty',
'Referer': 'https://cloud.baidu.com/product/ocr/general',
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
}
# 打开图片并对其使用 base64 编码
with open(img_path, 'rb') as f:
img = base64.b64encode(f.read())
data = {
'image': 'data:image/jpeg;base64,'+str(img)[2:-1],
'image_url': '',
'type': 'https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic',
'detect_direction': 'false'
}
# 开始调用 ocr 的 api
response = requests.post(
'https://cloud.baidu.com/aidemo', headers=headers, data=data)
# 设置一个空的列表,后面用来存储识别到的字符串
ocr_text = []
result = response.json()['data']
if not result.get('words_result'):
return []
# 将识别的字符串添加到列表里面
for r in result['words_result']:
text = r['words'].strip()
ocr_text.append(" ")
ocr_text.append(text)
wordfile.add_paragraph(ocr_text)
# 返回字符串列表
return ocr_text
'''
img_path 里面填图片路径,这里分两种情况讨论:
第一种:假设你的代码跟图片是在同一个文件夹,那么只需要填文件名,例如 test1.jpg (test1.jpg 是图片文件名)
第二种:假设你的图片全路径是 D:/img/test1.jpg ,那么你需要填 D:/img/test1.jpg
'''
for i in range(300, 400):
img_path10 = str(i) + ".jpg"
content = "".join(ocr(img_path10))
print(content)
# img_path = '2.jpg'
# # content 是识别后得到的结果
# content = "".join(ocr(img_path))
# # 输出结果
# print(content)
save_path = r'E:\vs\前400.docx'
wordfile.save(save_path)
4.3.3 구체적인 설명
Python을 사용하여 이미지 텍스트 인식을 빠르게 실현(코드 30줄)
4.3.4 기존 문제
이것은 본질적으로 api 인터페이스를 호출하는 것이므로 여러 번 호출하면 무효화되고 계속 사용할 수 있기까지 시간이 걸립니다.
5. 참고 사항
python.exe
일부 라이브러리를 설치했지만 컴파일할 때 라이브러리를 찾을 수 없다는 문제를 피하기 위해 Python을 설치한 경로에서 Python 인터프리터를 선택하는 것이 가장 좋습니다 .
--------------------------------이하 미완성----------------- --------------
발생하는 문제
Python이 터미널에서 pip를 통해 패키지를 설치한 후에도 Pycharm에서 솔루션을 계속 사용할 수 없습니다.