IBM Personal Insights语法错误

2024-05-20 09:10:05 发布

您现在位置:Python中文网/ 问答频道 /正文

在IBM Watson Personality Insights API于今年年底关闭之前,我正在尝试学习它的基本工作原理。我有一个基本的文本文件,我想分析,但我有麻烦让代码正常运行I have been trying to follow along on the official sits instructions,但我被卡住了。我做错了什么?(我在下面的代码中涂抹了我的钥匙)

from ibm_watson import PersonalityInsightsV3
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator

authenticator = IAMAuthenticator('BlottedOutKey')
personality_insights = PersonalityInsightsV3(
    version='2017-10-13',
    authenticator=authenticator
)

personality_insights.set_service_url('https://api.us-west.personality-insights.watson.cloud.ibm.com')
with open(join(C:\Users\AWaywardShepherd\Documents\Data Science Projects\TwitterScraper-master\TwitterScraper-master\snscrape\python-wrapper\Folder\File.txt), './profile.json')) as profile_json:
    profile = personality_insights.profile(
        profile_json.read(),
        content_type='text/plain',
        consumption_preferences=True,
        raw_scores=True)
    .get_result()
print(json.dumps(profile, indent=2))

我一直收到以下难以描述的语法错误:

  File "<ipython-input-1-1c7761f3f3ea>", line 11
    with open(join(C:\Users\AWaywardShepherd\Documents\Data Science Projects\TwitterScraper-master\TwitterScraper-master\snscrape\python-wrapper\Folder\File.txt), './profile.json')) as profile_json:
                    ^ SyntaxError: invalid syntax

Tags: 代码fromimportmasterauthenticatorjsoncloudwatson
1条回答
网友
1楼 · 发布于 2024-05-20 09:10:05

那条open线有很多错误

  • join需要一个可写入的字符串,它将该字符串合并成一个字符串
  • 在Python中,字符串通过用引号括起来变成字符串(路径就是字符串!)
  • 您只将一个值传递给join,这使得它是多余的
  • open的第二个参数应该是模式,而不是文件名
  • 看起来您正试图用文件名附加目录,但要使其生效,目录不应以文件名结尾
  • 括号不匹配-您有2个开始括号和3个结束括号

在Python中,使用join连接字符串以进行聚集。通常这是一个路径和文件名。从当前工作目录获取路径并将其与路径联接

import os

file = os.path.join(os.getcwd(), 'profile.json')

在代码中只传入一个字符串,因此不需要使用join

使用open传递文件名和模式。模式类似于'r'表示读取模式。因此,带有连接的代码变为

import os

with open(os.path.join(os.getcwd(), 'profile.json'), 'r') as profile_json:

相关问题 更多 >