![](/img/trans.png)
[英]python AttributeError: 'mHID' object has no attribute 'dict'
[英]Python - AttributeError: 'dict' object has no attribute 'replace'
每当我运行下面的代码时,都会出现此错误:
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.")
你能帮忙的话,我会很高兴。 谢谢!
看来您只是想用screeenshoturl
替换键"Screenshot URL"
的screeenshoturl
。 如果是这样,那你就错了。 尝试这个:
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.