2017-12-30 60 views
0

IBM WatsonのNatural Language Understanding APIを使用してURLからキーワードおよびエンティティを取り戻しています。 JSONレスポンスを繰り返して、すべてのキーワードとエンティティを取得し、results.htmlファイルに値を設定します。IBM Watson API Pythonの結果を反復処理するときにエラーが発生する

私は、application.pyファイルとjinjaを使用するresults.htmlファイルの結果を反復しようとしています。

helpers.pyファイルはjson.dumpを返し、結果を反復処理できるようにapplication.pyファイルに送信しています。

しかし、私は次のエラーを取得しています:

TypeError: string indices must be integers 

私はこの問題を解決するためjson.loadと文字列と辞書対json.dumpを見てきましたが、私は得ることができません作業するコード。詳細が必要な場合は、私に知らせてください。私は今年の終わりまでにこれを理解する必要があります。前もって感謝します。ここで

はここhelpers.pyファイルである私のapplications.pyファイル

@app.route("/URL", methods=["GET", "POST"]) 
def URL(): 
"""Analyze URL.""" 

# if user reached route via POST (as by submitting a form via POST) 
if request.method == "POST": 

    # if nothing was entered return apology 
    if not request.form.get("URL"): 
     return apology("please enter a URL") 
    URL = request.form.get("URL") 

    # analyze URL using analyze function in helpers.py 
    results = analyze(request.form.get("URL")) 

    for item in results: 
     keywords = item["keywords"]["text"] 
     entities = item["entities"]["text"] 

    return render_template("results.html", results=results, URL=URL) 

    # check if URL is valid 
    if not results: 
     return apology("this is not a valid URL") 

else: 
    return render_template("url.html") 

です。ここで

def analyze(URL): 

natural_language_understanding = NaturalLanguageUnderstandingV1(
    version='2017-02-27', 
    username='MUSTGETYOURUSERNAME', 
    password='MUSTGETYOURPASSWORD') 

response = natural_language_understanding.analyze(
    url=URL, 
    features=Features(entities=EntitiesOptions(), keywords=KeywordsOptions())) 

return (json.dumps(response, indent=2)) 

は神社を使用してresults.htmlファイルである:ここで起こっていくつかの混乱があります

[ 
    { 
    "text": "Android apps", 
    "relevance": 0.926516 
    }, 
    { 
    "text": "Chrome OS", 
    "relevance": 0.878045 
    }, 
    { 
    "text": "Sorry Android fanboys", 
    "relevance": 0.696885 
    }, 
    { 
    "text": "Android tablet", 
    "relevance": 0.695471 
    }, 
    { 
    "text": "absolutely wonderful Android", 
    "relevance": 0.672889 
    }, 
    { 
    "text": "Chrome OS beta", 
    "relevance": 0.626619 
    }, 
    { 
    "text": "Android Police", 
    "relevance": 0.592994 
    }, 
    { 
    "text": "Chrome OS devices", 
    "relevance": 0.566831 
    }, 
    { 
    "text": "count Android", 
    "relevance": 0.563911 
    }, 
    { 
    "text": "dominant Google OS", 
    "relevance": 0.553724 
    }, 
    { 
    "text": "Chrome Unboxed", 
    "relevance": 0.540076 
    }, 
    { 
    "text": "overall tablet sales", 
    "relevance": 0.511826 
    }, 
    { 
    "text": "inexpensive Google rival", 
    "relevance": 0.498259 
    }, 
    { 
    "text": "half incremental improvements", 
    "relevance": 0.468663 
    }, 
    { 
    "text": "standard operating procedure", 
    "relevance": 0.45946 
    }, 
    { 
    "text": "uncommon Chromebook form", 
    "relevance": 0.456969 
    }, 
    { 
    "text": "content consumption machines", 
    "relevance": 0.451775 
    }, 
    { 
    "text": "absolute best pieces", 
    "relevance": 0.450763 
    }, 
    { 
    "text": "content creation ones", 
    "relevance": 0.450345 
    }, 
    { 
    "text": "rich new fusion", 
    "relevance": 0.446127 
    }, 
    { 
    "text": "Amazon Fire tablet", 
    "relevance": 0.444685 
    }, 
    { 
    "text": "selling tablet", 
    "relevance": 0.444241 
    }, 
    { 
    "text": "tablet operating", 
    "relevance": 0.440434 
    }, 
    { 
    "text": "Google Pixelbook", 
    "relevance": 0.440007 
    }, 
    { 
    "text": "Google store", 
    "relevance": 0.439719 
    }, 
    { 
    "text": "cheap tablets", 
    "relevance": 0.408395 
    }, 
    { 
    "text": "immortal highlander", 
    "relevance": 0.404233 
    }, 
    { 
    "text": "disparate OSes", 
    "relevance": 0.401626 
    }, 
    { 
    "text": "laptop space", 
    "relevance": 0.40117 
    }, 
    { 
    "text": "detachable two-in-one", 
    "relevance": 0.396257 
    }, 
    { 
    "text": "pleasant surprises", 
    "relevance": 0.394027 
    }, 
    { 
    "text": "additional oomph", 
    "relevance": 0.393127 
    }, 
    { 
    "text": "Samsung", 
    "relevance": 0.391534 
    }, 
    { 
    "text": "flashy Chromebook", 
    "relevance": 0.391359 
    }, 
    { 
    "text": "sleek Chromebook", 
    "relevance": 0.390035 
    }, 
    { 
    "text": "smaller devices", 
    "relevance": 0.389106 
    }, 
    { 
    "text": "operating systems", 
    "relevance": 0.388958 
    }, 
    { 
    "text": "new feature", 
    "relevance": 0.388395 
    }, 
    { 
    "text": "true multitasking", 
    "relevance": 0.388097 
    }, 
    { 
    "text": "tablet-like device", 
    "relevance": 0.387175 
    }, 
    { 
    "text": "two-in-one Chromebook", 
    "relevance": 0.385518 
    }, 
    { 
    "text": "nightmare fuel", 
    "relevance": 0.385284 
    }, 
    { 
    "text": "mouse-first OS—not", 
    "relevance": 0.385193 
    }, 
    { 
    "text": "parallel tasks", 
    "relevance": 0.381923 
    }, 
    { 
    "text": "budget device", 
    "relevance": 0.380932 
    }, 
    { 
    "text": "iPad", 
    "relevance": 0.35313 
    }, 
    { 
    "text": "news", 
    "relevance": 0.333007 
    }, 
    { 
    "text": "strides", 
    "relevance": 0.319667 
    }, 
    { 
    "text": "iOS", 
    "relevance": 0.318235 
    }, 
    { 
    "text": "thanks", 
    "relevance": 0.316534 
    } 
] 

[ 
    { 
    "type": "Company", 
    "text": "Google", 
    "relevance": 0.385564, 
    "disambiguation": { 
     "subtype": [ 
     "AcademicInstitution", 
     "AwardPresentingOrganization", 
     "OperatingSystemDeveloper", 
     "ProgrammingLanguageDeveloper", 
     "SoftwareDeveloper", 
     "VentureFundedCompany" 
     ], 
     "name": "Google", 
     "dbpedia_resource": "http://dbpedia.org/resource/Google" 
    }, 
    "count": 9 
    }, 
    { 
    "type": "Company", 
    "text": "Samsung", 
    "relevance": 0.204475, 
    "disambiguation": { 
     "subtype": [], 
     "name": "Samsung", 
     "dbpedia_resource": "http://dbpedia.org/resource/Samsung" 
    }, 
    "count": 4 
    }, 
    { 
    "type": "Location", 
    "text": "Chromebooks", 
    "relevance": 0.129986, 
    "disambiguation": { 
     "subtype": [ 
     "City" 
     ] 
    }, 
    "count": 2 
    }, 
    { 
    "type": "Company", 
    "text": "Amazon", 
    "relevance": 0.119948, 
    "disambiguation": { 
     "subtype": [], 
     "name": "Amazon.com", 
     "dbpedia_resource": "http://dbpedia.org/resource/Amazon.com" 
    }, 
    "count": 2 
    }, 
    { 
    "type": "Location", 
    "text": "US", 
    "relevance": 0.109124, 
    "disambiguation": { 
     "subtype": [ 
     "Region", 
     "AdministrativeDivision", 
     "GovernmentalJurisdiction", 
     "FilmEditor", 
     "Country" 
     ], 
     "name": "United States", 
     "dbpedia_resource": "http://dbpedia.org/resource/United_States" 
    }, 
    "count": 1 
    }, 
    { 
    "type": "Company", 
    "text": "Apple", 
    "relevance": 0.108271, 
    "disambiguation": { 
     "subtype": [ 
     "Brand", 
     "OperatingSystemDeveloper", 
     "ProcessorManufacturer", 
     "ProgrammingLanguageDesigner", 
     "ProgrammingLanguageDeveloper", 
     "ProtocolProvider", 
     "SoftwareDeveloper", 
     "VentureFundedCompany", 
     "VideoGameDeveloper", 
     "VideoGamePublisher" 
     ], 
     "name": "Apple Inc.", 
     "dbpedia_resource": "http://dbpedia.org/resource/Apple_Inc." 
    }, 
    "count": 1 
    }, 
    { 
    "type": "Quantity", 
    "text": "$500", 
    "relevance": 0.0746897, 
    "count": 1 
    }, 
    { 
    "type": "Quantity", 
    "text": "$50", 
    "relevance": 0.0746897, 
    "count": 1 
    } 
] 
+0

どのラインがエラーになりますか? – doctorlove

+0

ファイル "/home/ubuntu/workspace/project/application.py"、行70、URL キーワード= item ["keywords"] ["text"] TypeError:文字列インデックスは整数でなければなりません –

+0

「item」は文字列、 'item [" keywords "]'は文字列です。あなたの質問に 'print(item)'の出力を含めれば助けになります。 –

答えて

0

:ここ

{% extends "layout.html" %} 

{% block title %} 
Results 
{% endblock %} 

{% block main %} 
     <h2>Powered by IBM Watson's AI to recommend your #'s and @'s 
for tweeting</h2> 
     <p>{{URL}}</p> 
     {% for item in results %} 
      <tr> 
       <td>{{ item.keywords }}</td> 
       <td>{{ item.entities }}</td> 
      </tr> 
     {% endfor %} 

     <a class="twitter-share-button" 
href="https://twitter.com/intent/tweet">Tweet</a> 
{% endblock %} 

は、出力は次のようになります。あなたはWatson APIレスポンスを特にうまく扱っていません。また、このレスポンスが返ってくる形を誤解しているようです。

analyze関数は、Watson API呼び出しからの応答を処理します。 Watson APIは、サーバーから返されたJSON応答を、リストやdictなどのPythonオブジェクトに構文解析します。ただし、あなたのコードはjson.dumpsを呼び出して、それを文字列に変換し直します。このようにして、Watson APIがあなたのために行った作業の一部を元に戻します。 responsejson.dumpsに電話しないでください。ちょうどresponseを返してください。

(私はあなたが正式なIBMのドキュメントhereからこれを撮影した推測している:それはjson.dumpsに同じ呼び出しを持っていますが、Pythonのコードサンプルは、デモンストレーションのみを目的としてでいることがある)

これは、エラーを説明しますあなたは次のようになります:resultsは文字列なので、for item in resultsを使って反復すると、それぞれitemは1文字の文字列になります。

ただし、この変更を行うだけではコードを動作させるには不十分です。それはリストであるかのよう

for item in results: 
     keywords = item["keywords"]["text"] 
     entities = item["entities"]["text"] 

このコードは、リスト内の各itemはdictのことで、resultsを扱います:次に、我々はそれに問題がまだあるとして、エラーが発生したループを見ていますkeywordsプロパティとentitiesプロパティを含んでいます。言い換えれば、それはデータが以下のようになります前提としています。あなたはthe IBM documentation(上記にリンクされているのと同じページ)を詳しく見てみた場合

[ 
    { 
     "keywords": { "text": "abc123", ... }, 
     "entities": { "text": "def456", ... }, 
     ... 
    }, 
    { 
     "keywords": { "text": "cba321", ... }, 
     "entities": { "text": "fed654", ... }, 
     ... 
    }, 
    ... 
] 

しかし、応答は異なる形状に戻ってきます。特に

{ 
    "keywords": [ 
     { "text": "abc123", ... }, 
     { "text": "def456", ... } 
    ], 
    "entities": [ 
     { "text": "ghi789", ... } 
    ], 
    ... 
} 

keywordsentitiesは、トップレベルのオブジェクト/ dictの下に別々のリストであり、それらが同じ長さを持っていない可能性があります:それは、より多くのこのようになります。私はあなたの元のループが行うことになっていたかわからないんだけど、しかし

for item in results["keywords"]: 
     keyword_text = item["text"] 

    for item in results["entities"]: 
     entity_text = item["text"] 

:上記の代わりに、あなたのループの

は、おそらくより、以下のような何かをしたい、それはあなたのワトソンからデータをフェッチしますレスポンスを返し、取り出したデータは何も処理しません。

また、Jinjaテンプレートを変更して、2つの別々のループを含める必要があります。私はこれをあなたに任せます。

は最後に、次のようなコードを記述:

return render_template("results.html", results=results, URL=URL) 

    # check if URL is valid 
    if not results: 
     return apology("this is not a valid URL") 

それは、我々はすでに戻ってきた後にURLが有効であるかどうかを確認するには手遅れ!チェック(if not results)に到達できず、実行されません。このチェックを行の直後に移動します。results = analyze(...)

+0

ありがとうございました!私は実際には元々同じループを行っていましたが、動作させることができなかったので変更しました。私はそれがすべて私のジンジャーだったことを今気づきます。私はジンジャで変数を設定することができなかったことを認識していませんでした。私はあなたの正確なループを取って、ジンジャーに変換しました。 Idkなぜ私は私のPythonコードでそのループが必要だと思った。あなたのポイントでは、Watsonからのデータ応答を取得し、何もしません。 –

関連する問題