【发布时间】: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