簡體   English   中英

Python-AttributeError:“ dict”對象沒有屬性“ replace”

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM