【问题标题】:Python - AttributeError: 'dict' object has no attribute 'replace'Python - AttributeError:'dict'对象没有属性'replace'
【发布时间】:2019-08-02 08:56:50
【问题描述】:

每当我运行下面的代码时,我都会收到此错误:

AttributeError: 'dict' 对象没有属性 'replace'

我不确定如何解决这个问题。我想搜索 json 文件并找到“屏幕截图包”并将其替换为用户输入,但我得到了那个错误。

我的代码:

numberofscreenshots = input("How much screenshots do you want?: ")

if numberofscreenshots == "1":

    screenshoturl = input("Link to screenshot: ")

    with open('path/to/json/file','r') as f:
        data = f.read()

    data = json.loads(data)

    # Check the data before.
    print( data['tabs'][0]['views'][1]['screenshots'] )

    # Overwrite screenshots placeholders in template file if more then one.
    data['tabs'][0]['views'][1]['screenshots']  =  data['tabs'][0]['views'][1]['screenshots'][0]

    # Check after to make sure it worked.
    print( data['tabs'][0]['views'][1]['screenshots'] )

    # Now search for the screenshot option and add users input.
    screenshotplaceholdertext = {"Screenshot URL 1":screenshoturl}
    for removescreenshotplaceholders in data:
        for screenshotplaceholder, removescreenshotplaceholder in screenshotplaceholdertext.items():
            removescreenshotplaceholders = removescreenshotplaceholders.replace(screenshotplaceholder, removescreenshotplaceholder)
        data.replace(removescreenshotplaceholders)

    # Write data to JSON file.
    with open('path/to/json/file', 'w') as f:
        f.write(json.dumps(data))
else:
    print("Something went wrong.")

任何帮助都会很好。谢谢!

【问题讨论】:

  • 这个错误对我来说似乎是不言自明的。字典上没有 replace() 方法。此外,即使确实有,也可能需要两个参数......
  • 你的代码没有意义。你为什么要遍历一个你首先只有一个键的dict,我们不知道数据是什么样子或者你的indended结果是什么。
  • @Jab: 那些数据在这里:stackoverflow.com/questions/55090638/… OP继续解决问题,但是由于问题涉及另一个问题,它现在创建了一个新主题,并且忘记添加示例的内容JSON 数据。
  • @Jim:.replace() 方法不能用于字典数据类型。可以找到可用于字典的方法,例如。这里:w3schools.com/python/python_ref_dictionary.asp 要更新现有的字典键,只需使用.update() 方法,正如@Jab 在下面的代码中所说。我引用他的话:data['tabs'][0]['views'][1]['screenshots'].update({"Screenshot URL 1":screenshoturl}) 或使用分配运算符:data['tabs'][0]['views'][1]['screenshots'] = {"Screenshot URL 1":screenshoturl}。使用嵌套词汇很复杂。您必须小心重写的内容和位置。
  • @Jim:但是...我认为...您仍然使用不同的 JSON 文件格式。字典变量(原始)的格式如下:{u'url': u'Screenshot URL 1', u'fullSizeURL': u'Screenshot URL 1', u'accessibilityText': u'Screenshot'}'url' 键可能不会保留?!

标签: python


【解决方案1】:

您似乎只是想用screeenshoturl 替换键"Screenshot URL" 的值。如果是这样,那你就大错特错了。试试这个:

with open('path/to/json/file','r') as f:
    data = json.loads(f.read())

# Check the data before.
try:
    data['tabs'][0]['views'][1]['screenshots'][0]
except ValueError:
    print("No Screenshots")

# Overwrite screenshots placeholders.
data['tabs'][0]['views'][1]['screenshots']  =  data['tabs'][0]['views'][1]['screenshots'][0]

#from the error, I'm getting that data['tabs'][0]['views'][1]['screenshots']
#is now a dict, so there should only be one "Screenshot URL" key so no need
#to do any loops here, just replace the key.
data['tabs'][0]['views'][1]['screenshots'].update({"Screenshot URL":screenshoturl})

with open('path/to/json/file', 'w') as f:
    f.write(json.dumps(data))

【讨论】:

  • 感谢您的回答,经过一些修改以适应我的代码后,我得到了它的工作,但现在我想添加另一行以获取更多选项,例如“屏幕截图 URL 2”我将如何执行此操作?另外,如果您愿意,可以向我举例说明此代码的工作原理吗?
  • 如果您不知道它是如何工作的,那么您将需要对 dicts 的工作原理进行一些研究。但是,如果您想更新字典中的 2 个键,只需在更新字典中添加另一个键/值对,如下所示:data['tabs'][0]['views'][1]['screenshots'].update({"Screenshot URL":screenshoturl, "Screenshot URL 2":screenshoturl2})
  • 在我更新它以适应我的代码后它不起作用它只添加第一个这是它现在的样子data['tabs'][0]['views'][1]['screenshots'].update({"accessibilityText": "Screenshot","url": screenshoturl1,"fullSizeURL": screenshoturl1, "accessibilityText": "Screenshot","url": screenshoturl2,"fullSizeURL": screenshoturl2})
  • 只添加第一个,不添加第二个。
  • 第一个什么?截图?
猜你喜欢
  • 2020-09-11
  • 2018-06-22
  • 2018-10-13
  • 2022-12-22
  • 2018-05-10
  • 2014-09-02
  • 2019-09-12
  • 2014-06-19
  • 1970-01-01
相关资源
最近更新 更多