0

在下面的构造中,我试图通过我的 Web 服务传递一个 JSON 对象。作为一项新要求,我必须传递sent下面代码中的字典对象。你能指导我如何将字典添加到 JSON 对象吗?

if plain_text is not None:
        blob = TextBlob(plain_text)
        sentiment = TextBlob(plain_text)
        sent = {}
        for sentence in blob.sentences:
            sent[sentence] =sentence.sentiment.polarity
        print sent
        return json.dumps(
            {'input' : plain_text, 
             'Polarity': sentiment.polarity,                 
             #'sent': json.dumps(sent) # this is where I am stuck as this 'sent' is a dict
             },
            indent=4)

如果我取消注释该行,我会收到以下错误:

Exception:

TypeError('keys must be a string',)
Traceback:
Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\bottle-0.12.7-py2.7.egg\bottle.py", line 862, in _handle
    return route.call(**args)
  File "C:\Python27\lib\site-packages\bottle-0.12.7-py2.7.egg\bottle.py", line 1729, in wrapper
    rv = callback(*a, **ka)
  File "C:\Users\hp\Desktop\RealPy\WebServices\bottle\server_bckup.py", line 53, in sentimentEngine
    'sent': json.dumps(sent),
  File "C:\Python27\lib\json\__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "C:\Python27\lib\json\encoder.py", line 201, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "C:\Python27\lib\json\encoder.py", line 264, in iterencode
    return _iterencode(o, 0)
TypeError: keys must be a string
4

1 回答 1

0

在 JSON 中,字典键必须是字符串。你有一个 Python 字典sent,你想序列化成 JSON。这失败了,因为您的字典sent的键不是字符串,而是textblob.blob.Sentence实例。

如果有意义,您可以将代码更改为:

    for sentence in blob.sentences:
        sent[str(sentence)] = sentence.sentiment.polarity

或者,您可以自定义 Python JSON 编码器以了解如何序列化 TextBlob 句子。

于 2014-11-15T18:10:57.907 回答