from ecloud import CMSSEcloudOcrClient import json import os from collections import OrderedDict accesskey = '357c19f09220408cb3650e8ca8a418c7' secretkey = 'f5f4f10272284ec3829460e0a65f5cd2' url = 'https://api-wuxi-1.cmecloud.cn:8443' def request_webimage(imagepath): requesturl = '/api/ocr/v1/webimage' try: ocr_client = CMSSEcloudOcrClient(accesskey, secretkey, url) response = ocr_client.request_ocr_service_file(requestpath=requesturl, imagepath=imagepath) json_data = json.loads(response.text, object_pairs_hook=OrderedDict) # 使用OrderedDict保证输出的文本有序 print(json.dumps(json_data, indent=4, ensure_ascii=False)) # 使用json.dumps()方法美化输出 except ValueError as e: print(e) if __name__ == "__main__": folder_path = "C:\\Users\\Administrator\\Desktop\\pics" # 修改为实际的文件夹路径 for filename in os.listdir(folder_path): if filename.endswith(".jpg") or filename.endswith(".jpeg") or filename.endswith(".png"): imagepath = os.path.join(folder_path, filename) request_webimage(imagepath)帮我修改代码把输出的jason格式的数据保存在txt文件中
时间: 2024-02-29 08:57:15 浏览: 144
你好,请尝试以下修改:
```python
from ecloud import CMSSEcloudOcrClient
import json
import os
from collections import OrderedDict
accesskey = '357c19f09220408cb3650e8ca8a418c7'
secretkey = 'f5f4f10272284ec3829460e0a65f5cd2'
url = 'https://api-wuxi-1.cmecloud.cn:8443'
def request_webimage(imagepath):
requesturl = '/api/ocr/v1/webimage'
try:
ocr_client = CMSSEcloudOcrClient(accesskey, secretkey, url)
response = ocr_client.request_ocr_service_file(requestpath=requesturl, imagepath=imagepath)
json_data = json.loads(response.text, object_pairs_hook=OrderedDict)
# 使用OrderedDict保证输出的文本有序
print(json.dumps(json_data, indent=4, ensure_ascii=False)) # 使用json.dumps()方法美化输出
# 将数据保存到txt文件
with open('output.txt', 'a', encoding='utf-8') as f:
f.write(json.dumps(json_data, indent=4, ensure_ascii=False))
f.write('\n') # 每个json数据之间换行分隔
except ValueError as e:
print(e)
if __name__ == "__main__":
folder_path = "C:\\Users\\Administrator\\Desktop\\pics" # 修改为实际的文件夹路径
for filename in os.listdir(folder_path):
if filename.endswith(".jpg") or filename.endswith(".jpeg") or filename.endswith(".png"):
imagepath = os.path.join(folder_path, filename)
request_webimage(imagepath)
```
修改后的代码在每次输出json数据时,会将数据保存到当前目录下的`output.txt`文件中。每个json数据之间用换行符分隔。
阅读全文