码迷,mamicode.com
首页 > 其他好文 > 详细

项目完成进度二

时间:2020-03-14 00:52:03      阅读:65      评论:0      收藏:0      [点我收藏+]

标签:获取数据   oauth   app   pre   pen   port   com   col   body   

今天主要做关键词的提取和机器学习方面的学习

 

关键词提取调用了百度的api接口进行自然语言的处理,但是可能是我数据的原因,有好多提取不成功还不是太满意

代码

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import codecs
import json
import requests

APIKey=RU8P5LjWWfmEDrR5bhiSGhZc
SecretKey=OnePfLjp8kOBL8aPIHPPvFiTz5BeVDdI
list = []
#创建请求url
def get_url():
    url=0
    #通过API Key和Secret Key获取access_token
    AccessToken_url=https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={}&client_secret={}.format(APIKey,SecretKey)
    res = requests.post(AccessToken_url)#推荐使用post
    json_data = json.loads(res.text)
    #print(json.dumps(json_data, indent=4, ensure_ascii=False))
    if not json_data or access_token not in json_data:
        print("获取AccessToken的json数据失败")
    else:
        accessToken=json_data[access_token]
        #将得到的access_token加到请求url中
        url=https://aip.baidubce.com/rpc/2.0/nlp/v1/keyword?charset=UTF-8&access_token={}.format(accessToken)
    return url

# 提取项目名称
def diqu():
    f = codecs.open(jianjei.txt, mode=r, encoding=utf-8)  # 打开txt文件,以‘utf-8’编码读取
    line = f.readline()  # 以行的形式进行读取文件
    while line:
        a = line.split()
        b = a[0:1]  # 这是选取需要读取的位数
        list.append(b)  # 将其添加在列表之中
        line = f.readline()
    f.close()



#创建请求,获取数据
def get_tag(url,title,content):
    tag=‘‘#存储得到的关键词
    #创建Body请求
    body={
        "title": title,
        "content":content
    }
    body2 = json.dumps(body)#将字典形式的数据转化为字符串,否则报错
    #创建Header请求
    header={
        content-type: application/json
    }
    res = requests.post(url,headers=header,data=body2)# 推荐使用post
    json_data = json.loads(res.text)
    if not json_data or error_code in json_data:
        #print(json.dumps(json_data, indent=4, ensure_ascii=False))
        print("获取关键词的Json数据失败")
        with open(guanjianzi.txt, a+, encoding="utf-8") as q:
            q.write("\n")

    else:
        #print(json.dumps(json_data, indent=4, ensure_ascii=False))
        for item in json_data[items]:
            tag=tag+item[tag]+ 
        tags=tag.strip()#去除前后空格
        print(tags)
        with open(guanjianzi.txt, a+, encoding="utf-8") as q:
            q.write(tags+"\n")
        return tags

if __name__ == __main__:
    diqu()

    url = get_url()
    title = 关键词提取和分析


    for i in list:
        get_tag(url, title, i)

 

项目完成进度二

标签:获取数据   oauth   app   pre   pen   port   com   col   body   

原文地址:https://www.cnblogs.com/xuange1/p/12489998.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!