【问题标题】:How to access the object in python? [closed]如何在python中访问对象? [关闭]
【发布时间】:2016-05-11 22:30:52
【问题描述】:
TEXT_TO_READ = """{

    "tts_type": "text",

    "tts_input": "I am Hungry"

}"""

我的旧代码:

scriptPath = os.path.abspath(__file__)
scriptPath = os.path.dirname(scriptPath)
line = os.path.join(scriptPath, "input.txt")
TEXT_TO_READ["tts_input"] = line

我正在尝试访问 TEXT_TO_READ 的 tts_input。但我想,我犯了一个错误。有人可以帮我吗,如何访问这个?

我无法阅读我的代码的第 4 行并得到错误:TEXT_TO_READ[tts_input] = line AttributeError:“str”对象没有属性“tts_input”。有人可以帮我吗?

【问题讨论】:

  • 您的代码不会生成该错误消息。
  • 请将原代码放回原处,这样答案的上下文就可以理解了。如果您想展示如何修改代码并提出后续问题,请将其附加到问题而不是替换。
  • 请阅读“How to Ask”和“minimal reproducible example”。

标签: python arrays python-2.7 object


【解决方案1】:

您需要将TEXT_TO_READ 解析为一个对象。您可以使用 python 库 json 来实现。

import json
TEXT_TO_READ = """{"tts_type": "text","tts_input": "I am Hungry"}"""
TEXT_TO_READ = json.loads(TEXT_TO_READ)
# rest of the code
TEXT_TO_READ["tts_input"] = line

当然,如果在代码中定义了TEXT_TO_READ 字符串(不是从数据库中提取或其他,请使用@Deleisha 建议的修改)。 但是,如果您需要将其作为字符串,则 json.loads() 会将其解析为对象。

更新

由于您在更新的问题中有另一个错误,我将更新我的答案。 在您的新代码中,您有

TEXT_TO_READ1 = json.loads(TEXT_TO_READ)

以后

TEXT_TO_READ["tts_input"] = line

您所做的是将对象保存到 TEXT_TO_READ1 并再次尝试从字符串中提取“tts_input”属性。请修改为TEXT_TO_READ1["tts_input"] = line

更新 2

好的,所以,如果我正确理解了您的代码,Request.add_json_parameter() 应该接受 STRING 作为 data 参数。在分配 TEXT_TO_READ["tts_input"] = line 中,您只想更新原始字符串。之后,您应该使用 json.dumps() 再次将其转换回字符串

因此,在这一行之后

TEXT_TO_READ["tts_input"] = line

添加

TEXT_TO_READ = json.dumps(TEXT_TO_READ)

更新 3(作为评论的答案)

你必须改变

line = os.path.join(scriptPath, "input.txt")
TEXT_TO_READ["tts_input"] = line

到这里

line = os.path.join(scriptPath, "input.txt")
TEXT_TO_READ["tts_input"] = open(line, "r").read()

为了实际读取文件的内容。

【讨论】:

  • 我如上修改了我的代码。但我得到的错误是: Traceback (last recent call last): File ".\tts.py", line 213, in body, boundary = request.encode() File ".\tts.py",第 98 行,在编码 body.write(parameter.encode()) 文件中 ".\tts.py",第 54 行,在编码 body.write(self.data) TypeError: 'dict' 没有缓冲区接口跨度>
  • @sam:这是不同的(尽管可能相关)错误,它不在您向我们展示的代码中。
  • 我如上修改了我的代码 - 得到错误 - Traceback(最近一次调用最后):文件“.\tts.py”,第 191 行,在 TEXT_TO_READ["tts_input"] = line TypeError: 'str' 对象不支持项目分配
  • @sam 你需要在那里使用TEXT_TO_READ1
  • 更新了我的答案。 @Barmar,是的。希望这只是一个错字
【解决方案2】:

您正在尝试访问字符串。进行以下更改

TEXT_TO_READ = {
    "tts_type": "text",
    "tts_input": "I am Hungry"
}

【讨论】:

  • 我无法改变这一点。这是来自服务器的回复。你能告诉我如何访问字符串吗?
  • 哦,在这种情况下,您需要使用@kecer 回答的json.loads() 函数
  • 我更新了我的完整代码。我收到的错误是: Traceback (last recent call last): File ".\tts.py", line 213, in body, boundary = request.encode() File ".\tts.py", line 98、在encode body.write(parameter.encode())文件".\tts.py"第54行,在encode body.write(self.data) TypeError: 'dict'没有缓冲区接口
猜你喜欢
  • 2021-08-14
  • 1970-01-01
  • 1970-01-01
  • 2013-06-19
  • 1970-01-01
  • 1970-01-01
  • 2014-03-13
  • 1970-01-01
  • 2018-07-07
相关资源
最近更新 更多