0

我正在尝试了解 IBM Watson Personality Insights API 在今年年底关闭之前的工作原理。我有一个要分析的基本文本文件,但我无法让代码正常运行。我一直在尝试按照官方的说明进行操作,但我被卡住了。我究竟做错了什么?(我已经在下面的代码中涂抹了我的钥匙)。

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
4

1 回答 1

2

open那条线有很多错误。

  • join 期待一个 itterable ,它将它连接成一个字符串。
  • 在 Python 中,字符串通过用引号括起来变成字符串(路径就是字符串!)
  • 您只将一个值传递给连接,这使得它变得多余。
  • open 的第二个参数应该是模式,而不是文件名。
  • 看起来您正在尝试附加一个带有文件名的目录,但要使其正常工作,该目录不应以文件名结尾。
  • 括号不匹配 - 您有 2 个左括号和 3 个右括号。

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

import os

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

在您的代码中,您只传递一个字符串,因此无需使用连接。

使用open您传入文件名和模式。该模式类似于'r'指示读取模式。所以带有连接的代码就变成了。

import os

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

于 2021-03-12T10:39:58.237 回答