【问题标题】:IBM Personality Insights Syntax ErrorsIBM Personality Insights 语法错误
【发布时间】:2021-06-08 22:08:35
【问题描述】:

我正在尝试了解 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

【问题讨论】:

    标签: python syntax-error ibm-watson personality-insights


    【解决方案1】:

    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:
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-17
      • 2020-05-13
      • 2018-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-21
      • 1970-01-01
      相关资源
      最近更新 更多