User:Nikki/pywikibot

From Wikidata
Jump to navigation Jump to search

This is some code using pywikibot that I wrote a few years ago which let me add references at the same time as adding or editing a statement, and some examples of how the functions are used.

# License: CC0

from collections import OrderedDict
import pywikibot
import uuid

def attachSources(claim, sourcestoadd):
	sources = OrderedDict()
	for source in sourcestoadd:
		prop = source.getID()
		sources[prop] = []
		sources[prop].append(source)
	claim.sources = [sources]

def detachSources(claim, sourcestorem):
	sources = OrderedDict()
	for source in sourcestorem:
		prop = source.getID()
		sources[prop] = []
		sources[prop].append(source)
	claim.sources.remove(sources)

def addClaimWithSources(item, claim):
	guid = "%s$%s" % (item.id, uuid.uuid4())
	claim.snak = guid.upper()
	claim.on_item = item
	site.save_claim(claim)

def saveClaim(claim):
	if not claim.on_item:
		claim.on_item = item
	site.save_claim(claim)

###

site = pywikibot.Site("wikidata", "wikidata")
repo = site.data_repository()

item = pywikibot.ItemPage(site, "Q4115189")
item.get()

# Create claim objects for the reference section
statedin = pywikibot.Claim(repo, u"P248", isReference=True)
statedinitem = pywikibot.ItemPage(repo, "Q13406268")
statedin.setTarget(statedinitem)

published = pywikibot.Claim(repo, u"P577", isReference=True)
date = pywikibot.WbTime(year=2018, month=6, day=1)
published.setTarget(date)

# Create object for the main statement
claim = pywikibot.Claim(repo, u"P31")
target = pywikibot.ItemPage(repo, "Q13406268")
claim.setTarget(target)

# Add the reference claims to the statement, then save as a single edit
attachSources(claim, [statedin, published])
addClaimWithSources(item, claim)

# Create a statement with "unknown value" and references
claim2 = pywikibot.Claim(repo, u"P31")
claim2.setSnakType("somevalue")
attachSources(claim2, [statedin, published])
addClaimWithSources(item, claim2)

# Replace P143 references with our new reference on each existing P31 statement
for claim in item.claims["P31"]:
	sources = claim.getSources()
	source = sources[0]
	if len(source) == 1 and "P143" in source.keys():
		detachSources(claim, [source["P143"][0]])
		attachSources(claim, [statedin, published])
		saveClaim(claim)