用户:肆oPIP查看:0 回复:3 评论:0 创建时间:2022-05-06T14:08:08
【作品展示】

【作品介绍】
大家看,我在电脑上拍的图片(狗头保命)
【作品源代码】
# -*- coding: utf-8 -*-
#导入库文件,在库管理中安喵aidu-api库,json5库,urllib3库
import urllib
import urllib.request
import json
import random
import requests
#调用写诗模型:调用写诗模型.py定义了调用写诗模型的方法,请将程序代码复制到本文件中。
#get_token_key()方法可以获取访问令牌并返回
def get_token_key():
url = 'https://aip.baidubce.com/oauth/2.0/token'
data = {
'grant_type': 'client_credentials', # 固定值
'client_id': 'R9wzWhYqac9SX9ATmC6jnZeh', # 在开放平台注册后所建应用的API Key
'client_secret': 'dtFOvUymIAOslPEi0ar0qVRjv1x9G2ou' # 所建应用的Secret Key
}
res = requests.post(url, data=data)
res = res.json()
token_key = res['access_token']
return token_key
#创作古诗:创作古诗.py定义了使用写诗模型生成古诗、输出古诗的方法,请将程序代码复制到本文件中。
def get_poem(content):
token = get_token_key()
url = 'https://aip.baidubce.com/rpc/2.0/nlp/v1/poem'
params = dict()
params['index'] = random.randint(0, 10)
params['text'] = content
params = json.dumps(params).encode('utf-8')
access_token = token
url = url + "?access_token=" + access_token
request = urllib.request.Request(url=url, data=params)
request.add_header('Content-Type', 'application/json')
response = urllib.request.urlopen(request)
content = response.read()
if content:
content = content.decode('utf-8')
data = json.loads(content)
return data
print(data)
else:
return '', ''
#parse_poem(data)方法可以解析生成的诗句并输出,data为调用智能写诗生成的有效数据
def parse_poem(data):
title = data['poem'][0]['title'] # 诗的题(title)
poem = data['poem'][0]['content'].replace('\t', '\n') # 诗的内容(content)
print(title) # 输出题目
print(poem) # 输出内容
print()
return title, poem # 返回题目和内容
#用户输入新的关键词,创作古诗。
if __name__ == '__main__':
topic = input("请输入诗歌主题(不超过5个汉字):") #请用户输入诗歌主题
data = get_poem(topic) # 使用生成古诗方法,创作主题为topic的古诗,将横线替换为相应代码
parse_poem(data) #输出古诗
【提示】
部分含有Python第三方库相关内容的作品,在海龟编辑器网页端无法运行哦!如遇到这种情况,可以打开下面的链接,下载海龟编辑器客户端:
https://python.codemao.cndef get_token_key():
url = '喵喵喵'
data = {
'grant_type': 'client_credentials', # 固定值
'client_id': 'R9wzWhYqac9SX9ATmC6jnZeh', # 在开放平台注册后所建应用的API Key
'client_secret': 'dtFOvUymIAOslPEi0ar0qVRjv1x9G2ou' # 所建应用的Secret Key
}
res = requests.post(url, data=data)
res = res.json()
token_key = res['access_token']
return token_key点赞0
评论