import pywikibot
from pywikibot import pagegenerators as pg

site = pywikibot.Site("test", "wikidata")
repo = site.data_repository()
with open('page_codes.txt', 'r', encoding='utf-8') as f:
    codes = f.read().split()
property = "P106"
error_dict = {"Q5967378": "Q18844224",    #фантастика - писатель-фантаст
              "Q156035": "Q16287483"     #публицистика - публицист
               #"Q753": "Q2722041",   #copper - "element": "color"
              #"Q25381": "Q679355",   #amber - "material": "color"
              #"Q134862": "Q5069879", #champagne - "drink": "color"
              #"Q1090": "Q317802",    #silver - "element": "color"
              #"Q1173": "Q797446",    #burgundy - "region": "color
              #"Q13411121": "Q5148721", #peach - "fruit": "color"
              }

def correct_claim(generator, key):
    for page in generator:
        item_dict = page.get()
        claim_list = item_dict["claims"][property]
        for claim in claim_list:
            trgt = claim.getTarget()
            if trgt.id == key:
                print("Correcting {} to {}".format(key, error_dict[key]))
                correct_page = pywikibot.ItemPage(repo, error_dict[key], 0)
                claim.changeTarget(correct_page)

for key in error_dict:
    wdq = "CLAIM[{}:{}]".format(property[1:], key[1:])
    generator = pg.WikidataQueryPageGenerator(wdq, site)
    generator = site.preloadpages(generator, pageprops=True)
    correct_claim(generator, key)