0

我正在尝试使用 IBM DataScienceExperience 中的对象存储将数据从 DataFrame 文件发布到 Watson Personality Insights API。

我已将 txt 文件加载到 ObjectStorage 并创建了一个 DataFrame。工作正常。不明白如何将数据框中的数据发布到 API。提供的文档并没有为我指明正确的方向。

这就是我所做的

from io import StringIO
import requests
import json
import pandas as pd

def get_object_storage_file_with_credentials(container, filename):
    """This functions returns a StringIO object containing
    the file content from Bluemix Object Storage."""

    url1 = ''.join(['https://identity.open.softlayer.com', '/v3/auth/tokens'])
    data = {
        'auth': {
            'identity': {
                'methods': ['password'],
                'password': {
                    'user': {
                        'name': 'UID UID UID',
                        'domain': {
                            'id': 'ID ID ID'
                        },
                    'password': 'PASS PASS'
                    }
                }
            }
        }
    }
    headers1 = {'Content-Type': 'application/json'}
    resp1 = requests.post(url=url1, data=json.dumps(data), headers=headers1)
    resp1_body = resp1.json()

    for e1 in resp1_body['token']['catalog']:
        if(e1['type']=='object-store'):
            for e2 in e1['endpoints']:
                if(e2['interface']=='public'and e2['region']=='dallas'):
                    url2 = ''.join([e2['url'],'/', container, '/', filename])

    s_subject_token = resp1.headers['x-subject-token']
    headers2 = {'X-Auth-Token': s_subject_token, 'accept': 'application/json'}
    resp2 = requests.get(url=url2, headers=headers2)

    return StringIO(resp2.text)

PI_text = get_object_storage_file_with_credentials('MyDSXProjects', 'myPI.txt')

接下来我想将DataFrame内容发布到我想知道的API,希望有人可以提供提示......我的Python知识在这里缺乏。

4

1 回答 1

0

根据Watson Personality Insights API 参考,您可以提供文本、HTML 或 JSON 输入。您的数据集可用作熊猫数据框。尝试将 DataFrame 中的相关列转换为文本格式。例如通过:

pi_api_text = PI_text['<TEXT_COLUMN>'].str.cat(sep='. ').encode('ascii', 'ignore')

确保已安装 Python 包:

pip install --upgrade watson-developer-cloud

获得文本格式的相关数据后,调用 Watson Personality Insights API。例如:

personality_insights = PersonalityInsightsV3(
 version='xxxxxxxxx',
 username='xxxxxxxxxx',
 password='xxxxxxxxxx')
profile = personality_insights.profile(
 pi_api_text, content_type='text/plain',
 raw_scores=True, consumption_preferences=True)

响应将是一个包含个性特征的 JSON 对象,您可以将其重新转换为 pandas 数据框。

于 2017-09-11T07:14:17.017 回答