2017-05-11 102 views
0

下面的一組代碼的工作時,我有簡短的文字,但是當我給它這種形式的一個較長的文字:https://pastebin.com/PLinyN65IBM沃森ToneAnalyzerV3 WatsonException:錯誤:無效JSON輸入,代碼:400

import os 
import json 
from watson_developer_cloud import ToneAnalyzerV3 
from glob import glob 

with open(credentials.txt) as cred: 
    data = cred.readlines() 
    UserName = data[0] 
    PassWord = data[1] 

tone_analyzer = ToneAnalyzerV3(
       username=UserName, 
       password=PassWord, 
       version='2016-05-19') 

pth = '../input/*.txt' 
txtFiles = glob(pth) 
for file in txtFiles: 
    baseName = os.path.basename(file) 
    name = baseName.split('.') 

with open(file) as f: 
    txt = f.read() 

    with open('../output/{}.json'.format(name[0]), 'w') as outFile: 
     json.dump(tone_analyzer.tone(text=txt, sentences='false'), outFile, separators=(',', ': '), indent=2) 

我得到錯誤:

WatsonException       Traceback (most recent call last) 
<ipython-input-6-d948e97e307e> in <module>() 
     8 
     9   with open('../output/{}.json'.format(name[0]), 'w') as outFile: 
---> 10    json.dump(tone_analyzer.tone(text=txt, sentences='false'), outFile, separators=(',', ': '), indent=2) 
    11 
    12  print('{}\n'.format(name[0])) 

/Library/Python/2.7/site-packages/watson_developer_cloud/tone_analyzer_v3.pyc in tone(self, text, tones, sentences) 
    51   data = {'text': text} 
    52   return self.request(method='POST', url='/v3/tone', params=params, 
---> 53        json=data, accept_json=True) 

/Library/Python/2.7/site-packages/watson_developer_cloud/watson_developer_cloud_service.pyc in request(self, method, url, accept_json, headers, params, json, data, files, **kwargs) 
    318    else: 
    319     error_message = self._get_error_message(response) 
--> 320    raise WatsonException(error_message) 

WatsonException: Error: Invalid JSON input, Code: 400 

當我嘗試手動輸入這個網絡鏈接文本:https://tone-analyzer-demo.mybluemix.net/

我得到的錯誤:request entity too large

請諮詢我如何從ToneAnalyzerV3以json格式獲得所需的音色分析分數。

回答

1

望着音分析器API瀏覽器,你可以看到有文字量的限制每個請求可以處理:

The Tone Analyzer service supports up to 128 KB of text, or about 1000 sentences. Sentences with less than three words cannot be analyzed.

Tone Analyzer API Explorer

您提供的文本是165743個字節(168 KB),這比服務支持的要大。我試圖輸入在API瀏覽器上面提供的文字和你有上面收到了同樣的錯誤:

{ 
    "code": 400, 
    "sub_code": "C00013", 
    "error": "Invalid JSON input" 
} 

當你需要使用一個文本輸入是最大128 KB的文本的下方的解決方案。