示例#1
0
def addPop(item, repo, iedzivotaji, y, m, d, iedzAts, lgia):
    #seriesprop = "P179"

    if y != '' and m != '' and d != '':
        pwbtime = pywikibot.WbTime(year=int(y), month=int(m), day=int(d))
    elif y != '' and (m == '' or d == ''):
        pwbtime = pywikibot.WbTime(year=int(y))

    #iedz. skaits
    newClaim = pywikibot.Claim(repo, 'P1082')
    newClaim.setTarget(pywikibot.WbQuantity(amount=iedzivotaji, site=repo))
    item.addClaim(newClaim)

    #laika brīdis
    newClaim_date = pywikibot.Claim(repo, 'P585', isQualifier=True)
    newClaim_date.setTarget(pwbtime)
    newClaim.addQualifier(newClaim_date)

    if iedzAts == "yes" and lgia != '' and lgia.isnumeric:
        #apg. izteikts
        newClaim_ref = pywikibot.Claim(repo, 'P248', isReference=True)
        newClaim_ref.setTarget(pywikibot.ItemPage(repo, u'Q16362112'))

        #lgia id
        newClaim_ref2 = pywikibot.Claim(repo, 'P2496', isReference=True)
        newClaim_ref2.setTarget(lgia)

        #pārb datums @todo: izvilkt no atsauces
        #	newClaim_ref3 = pywikibot.Claim(repo, 'P813', isReference=True)
        #	newClaim_ref3.setTarget(pywikibot.WbTime(year=now.year, month=now.month, day=now.day))

        #	newClaim.addSources([newClaim_ref, newClaim_ref2, newClaim_ref3])
        newClaim.addSources([newClaim_ref, newClaim_ref2])
示例#2
0
    def addDateProperty(self, itempage, datestring, property, refurl):
        '''
        Try to find a valid date and add it to the itempage using property
        :param itempage: The ItemPage to update
        :param datestring: The string containing the date
        :param property: The property to add (for example date of birth or date of death)
        :param refurl: The url to add as reference
        :return:
        '''
        dateregex = u'^(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d)$'
        monthregex = u'^(?P<year>\d\d\d\d)-(?P<month>\d\d)$'
        yearregex = u'^(?P<year>\d\d\d\d)$'

        datematch = re.match(dateregex, datestring)
        monthmatch = re.match(monthregex, datestring)
        yearmatch = re.match(yearregex, datestring)

        newdate = None
        if datematch:
            newdate = pywikibot.WbTime(year=int(datematch.group(u'year')),
                                       month=int(datematch.group(u'month')),
                                       day=int(datematch.group(u'day')))
        elif monthmatch:
            newdate = pywikibot.WbTime(year=int(monthmatch.group(u'year')),
                                       month=int(monthmatch.group(u'month')))
        elif yearmatch:
            newdate = pywikibot.WbTime(year=int(yearmatch.group(u'year')))
        else:
            return False

        newclaim = pywikibot.Claim(self.repo, property)
        newclaim.setTarget(newdate)
        itempage.addClaim(newclaim)
        self.addReference(itempage, newclaim, refurl)
    def parseDatestring(self, datestring):
        '''
        Try to parse the date string. Returns
        :param datestring: String that might be a date
        :return:  pywikibot.WbTime
        '''
        dateregex = u'^(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d)$'
        monthregex = u'^(?P<year>\d\d\d\d)-(?P<month>\d\d)$'
        yearregex = u'^(?P<year>\d\d\d\d)$'

        datematch = re.match(dateregex, datestring)
        monthmatch = re.match(monthregex, datestring)
        yearmatch = re.match(yearregex, datestring)

        newdate = None
        if datematch:
            newdate = pywikibot.WbTime(year=int(datematch.group(u'year')),
                                       month=int(datematch.group(u'month')),
                                       day=int(datematch.group(u'day')))
        elif monthmatch:
            newdate = pywikibot.WbTime(year=int(monthmatch.group(u'year')),
                                       month=int(monthmatch.group(u'month')))
        elif yearmatch:
            newdate = pywikibot.WbTime(year=int(yearmatch.group(u'year')))
        return newdate
示例#4
0
def iso_to_wbtime(date):
    """
    Convert ISO date string into WbTime object.

    Given an ISO date object (1922-09-17Z or 2014-07-11T08:14:46Z)
    this returns the equivalent WbTime object

    @param item: An ISO date string
    @type item: basestring
    @return: The converted result
    @rtype: pywikibot.WbTime
    """
    date = date[:len('YYYY-MM-DD')].split('-')
    if len(date) == 3 and all(is_int(x) for x in date):
        # 1921-09-17Z or 2014-07-11T08:14:46Z
        d = int(date[2])
        if d == 0:
            d = None
        m = int(date[1])
        if m == 0:
            m = None
        return pywikibot.WbTime(year=int(date[0]), month=m, day=d)
    elif len(date) == 1 and is_int(date[0][:len('YYYY')]):
        # 1921Z
        return pywikibot.WbTime(year=int(date[0][:len('YYYY')]))
    elif (len(date) == 2
          and all(is_int(x) for x in (date[0], date[1][:len('MM')]))):
        # 1921-09Z
        m = int(date[1][:len('MM')])
        if m == 0:
            m = None
        return pywikibot.WbTime(year=int(date[0]), month=m)

    # once here all interpretations have failed
    raise pywikibot.Error('An invalid ISO-date string received: ' % date)
示例#5
0
def addinceptiondate(creation_events, wdItem):
    dateString = None
    for creation_event in creation_events:
        try:
            dateString = creation_event.find('dcterms:date',
                                             physical_thing.nsmap).text
        except AttributeError:
            print("No date string")
    if dateString is None:
        return None
    else:
        dateList = dateString.split(' - ')
        # If there's one and only one year in the result, just send that
        if all(x == dateList[0]
               for x in dateList) and validateDate(dateList[0]):
            wikiInception = pywikibot.WbTime(year=dateList[0])
            inceptionClaim = pywikibot.Claim(repo, "P571")
            inceptionClaim.setTarget(wikiInception)
            wdItem.addClaim(
                inceptionClaim,
                summary=
                "Importing painting data from the Estonian Museum Portal MuIS")
            inceptionClaim.addSources(
                [statedin, muisidref, refdate],
                summary=
                "Importing painting data from the Estonian Museum Portal MuIS")
            print("Adding inception date")
        # If there's a year range, and the decade is the same, send decade + start and end of range as qualifiers
        elif len(dateList) == 2 and dateList[0][:3] == dateList[
                1][:3] and dateList[0].isdigit() and dateList[1].isdigit():
            wikiInception = pywikibot.WbTime(year=dateList[0],
                                             precision="decade")
            inceptionClaim = pywikibot.Claim(repo, "P571")
            inceptionClaim.setTarget(wikiInception)
            wdItem.addClaim(
                inceptionClaim,
                summary=
                "Importing painting data from the Estonian Museum Portal MuIS")
            earliestQual = pywikibot.Claim(repo, "P1319")
            earliestQual.setTarget(pywikibot.WbTime(year=dateList[0]))
            inceptionClaim.addQualifier(
                earliestQual,
                summary=
                "Importing painting data from the Estonian Museum Portal MuIS")
            latestQual = pywikibot.Claim(repo, "P1326")
            latestQual.setTarget(pywikibot.WbTime(year=dateList[1]))
            inceptionClaim.addQualifier(
                latestQual,
                summary=
                "Importing painting data from the Estonian Museum Portal MuIS")

            inceptionClaim.addSources(
                [statedin, muisidref, refdate],
                summary=
                "Importing painting data from the Estonian Museum Portal MuIS")
            print("Adding inception date")
        # Otherwise, it's too complicated and risks being bullcrap, so skip and do manually
        else:
            return None
示例#6
0
    def testQueriesWDStructures(self):
        """
        Queries using Wikibase page structures like ItemPage
        """

        q = query.HasClaim(PropertyPage(self.repo, "P99"))
        self.assertEqual(str(q), "claim[99]")

        q = query.HasClaim(PropertyPage(self.repo, "P99"),
                           ItemPage(self.repo, "Q100"))
        self.assertEqual(str(q), "claim[99:100]")

        q = query.HasClaim(99, [100, PropertyPage(self.repo, "P101")])
        self.assertEqual(str(q), "claim[99:100,101]")

        q = query.StringClaim(PropertyPage(self.repo, "P99"), "Hello")
        self.assertEqual(str(q), 'string[99:"Hello"]')

        q = query.Tree(ItemPage(self.repo, "Q92"), [1], 2)
        self.assertEqual(str(q), 'tree[92][1][2]')

        q = query.Tree(ItemPage(self.repo, "Q92"),
                       [PropertyPage(self.repo, "P101")], 2)
        self.assertEqual(str(q), 'tree[92][101][2]')

        self.assertRaises(
            TypeError, lambda: query.Tree(PropertyPage(
                self.repo, "P92"), [PropertyPage(self.repo, "P101")], 2))

        c = pywikibot.Coordinate(50, 60)
        q = query.Around(PropertyPage(self.repo, "P625"), c, 23.4)
        self.assertEqual(str(q), 'around[625,50,60,23.4]')

        begin = pywikibot.WbTime(site=self.repo, year=1999)
        end = pywikibot.WbTime(site=self.repo, year=2010, hour=1)

        # note no second comma
        q = query.Between(PropertyPage(self.repo, "P569"), begin)
        self.assertEqual(str(q), 'between[569,+00000001999-01-01T00:00:00Z]')

        q = query.Between(PropertyPage(self.repo, "P569"), end=end)
        self.assertEqual(str(q), 'between[569,,+00000002010-01-01T01:00:00Z]')

        q = query.Between(569, begin, end)
        self.assertEqual(
            str(q),
            'between[569,+00000001999-01-01T00:00:00Z,+00000002010-01-01T01:00:00Z]'
        )

        # try negative year
        begin = pywikibot.WbTime(site=self.repo, year=-44)
        q = query.Between(569, begin, end)
        self.assertEqual(
            str(q),
            'between[569,-00000000044-01-01T00:00:00Z,+00000002010-01-01T01:00:00Z]'
        )
 def test_nonexisting_qualifiers(self):
     """Test ItemClaimFilterPageGenerator on sample page using qualifiers the page doesn't have."""
     qualifiers = {
         'P370':
         pywikibot.WbTime(1950, 1, 1, precision=9, site=self.get_site()),
         'P232':
         pywikibot.WbTime(1960, 1, 1, precision=9, site=self.get_site()),
     }
     self._simple_claim_test('P463', self._get_council_page(), qualifiers,
                             False)
示例#8
0
    def wd_actualitzar_pob(self, propietat, poblacio, any_cens):
        # creem el Claim de població o fogatge, el que toqui
        pob_clm = pywikibot.Claim(self.repowd, propietat)
        pob_clm.setTarget(
            pywikibot.WbQuantity(amount=poblacio, site=self.repowd))

        # Ara, la URL de la referència
        urldelaref = pywikibot.Claim(self.repowd, 'P854')
        urldelaref.setTarget(
            "http://ced.uab.es/infraestructures/banc-de-dades-espanya-i-catalunya/evolucio-i-continuitat-dels-municipis-catalans-1497-2002/"
        )

        # Ara, la data, amb precisió d'any
        if any_cens <= 1582:
            calendari = 'http://www.wikidata.org/entity/Q1985786'  # julià
        else:
            calendari = 'http://www.wikidata.org/entity/Q1985727'  # gregorià
        datainfo = pywikibot.WbTime(year=any_cens,
                                    precision='year',
                                    calendarmodel=calendari)
        qualif = pywikibot.Claim(self.repowd, 'P585')
        qualif.setTarget(datainfo)

        # Un altre qualificador, mètode de determinació ('P459')
        qualif2 = pywikibot.Claim(self.repowd, 'P459')
        if propietat == 'P1082':
            # el mètode és el padró municipal d'habitants, o Q745221 si és població
            qualif2.setTarget(pywikibot.ItemPage(self.repowd, "Q745221"))
        elif propietat == 'P1538':
            # el mètode és el fogatge, o Q2361901 si és nombre de llars
            qualif2.setTarget(pywikibot.ItemPage(self.repowd, "Q2361901"))
        else:
            print u'Propietat incorrecta a wd_actualitzar_pob', propietat

        # Ara la referència "Editorial" ('P123') a Centre d'Estudis Demogràfics
        ref2 = pywikibot.Claim(self.repowd, 'P123')
        ref2.setTarget(pywikibot.ItemPage(self.repowd, "Q25892981"))  # CED

        # una altra referència: data de consulta (P813) = 25-11-19
        data_consulta = pywikibot.WbTime(year=2018,
                                         month=11,
                                         day=25,
                                         precision='day')
        data_item = pywikibot.Claim(self.repowd, 'P813')
        # construim l'item
        data_item.setTarget(data_consulta)

        # Construïm la llista de referències
        lrefs = [data_item, ref2, urldelaref]

        self.item.addClaim(pob_clm)
        pob_clm.addQualifier(qualif)
        pob_clm.addQualifier(qualif2)
        pob_clm.addSources(lrefs)
 def test_get_nationality(self):
     this_date1=pywikibot.WbTime(site=site,year=2009, month=12, day=31, precision='day')    
     
     res=get_nationality(pywikibot, repo, site, "Q13893333", this_date1)
     self.assertEqual(res,"Q142")
     res=get_nationality(pywikibot, repo, site, "Q16215626", this_date1)
     self.assertEqual(res,"Q212")       
     res=get_nationality(pywikibot, repo, site, "Q270555", this_date1)
     self.assertEqual(res,"Q35")   
     
     this_date2=pywikibot.WbTime(site=site,year=2019, month=12, day=31, precision='day')    
     res=get_nationality(pywikibot, repo, site, "Q270555", this_date2)
     self.assertEqual(res,"Q664")  
示例#10
0
 def get_wbtime(self, date):
     precision = precision_map[date.precision]  # sling to wikidata
     if date.precision <= sling.YEAR:
         return pywikibot.WbTime(year=date.year, precision=precision)
     if date.precision == sling.MONTH:
         return pywikibot.WbTime(year=date.year,
                                 month=date.month,
                                 precision=precision)
     if date.precision == sling.DAY:
         return pywikibot.WbTime(year=date.year,
                                 month=date.month,
                                 day=date.day,
                                 precision=precision)
     return None
示例#11
0
    def addDateOfBirthDeath(self, artistItem, refurl):
        '''

        :return:
        '''
        pywikibot.output(
            u'Getting the page at %s for the date of birth and date of death' %
            (refurl, ))
        page = requests.get(
            refurl, verify=False)  # Getting an incorrect certificate here

        fulldobregex = u'\<span itemprop\=\"birthDate\"\>(\d\d)\.(\d\d)\.(\d\d\d\d)\<\/span\>'
        partdobregex = u'\<span itemprop\=\"birthDate\"\>(\d\d\d\d)\<\/span\>'
        fulldobmatch = re.search(fulldobregex, page.text)
        partdobmatch = re.search(partdobregex, page.text)

        newdob = None
        if fulldobmatch:
            newdob = pywikibot.WbTime(year=int(fulldobmatch.group(3)),
                                      month=int(fulldobmatch.group(2)),
                                      day=int(fulldobmatch.group(1)))
        elif partdobmatch:
            newdob = pywikibot.WbTime(year=int(partdobmatch.group(1)))

        if newdob:
            newclaim = pywikibot.Claim(self.repo, u'P569')
            newclaim.setTarget(newdob)
            artistItem.addClaim(newclaim)
            self.addReference(artistItem, newclaim, refurl)

        fulldodregex = u'\<span itemprop\=\"deathDate\"\>(\d\d)\.(\d\d)\.(\d\d\d\d)\<\/span\>'
        partdodregex = u'\<span itemprop\=\"deathDate\"\>(\d\d\d\d)\<\/span\>'
        fulldodmatch = re.search(fulldodregex, page.text)
        partdodmatch = re.search(partdodregex, page.text)

        newdod = None
        if fulldodmatch:
            newdod = pywikibot.WbTime(year=int(fulldodmatch.group(3)),
                                      month=int(fulldodmatch.group(2)),
                                      day=int(fulldodmatch.group(1)))
        elif partdodmatch:
            newdod = pywikibot.WbTime(year=int(partdodmatch.group(1)))

        if newdod:
            newclaim = pywikibot.Claim(self.repo, u'P570')
            newclaim.setTarget(newdod)
            artistItem.addClaim(newclaim)
            self.addReference(artistItem, newclaim, refurl)
示例#12
0
 def make_stated_in_reference(self, ref_dict):
     prop = ref_dict["source"]["prop"]
     if ref_dict.get("published"):
         prop_date = ref_dict["published"]["prop"]
         date = ref_dict["published"]["value"]
     elif ref_dict.get("retrieved"):
         prop_date = ref_dict["retrieved"]["prop"]
         date = ref_dict["retrieved"]["value"]
     date_item = pywikibot.WbTime(**date)
     source_item = self.wdstuff.QtoItemPage(ref_dict["source"]["value"])
     source_claim = self.wdstuff.make_simple_claim(prop, source_item)
     if "reference_url" in ref_dict:
         ref_url = ref_dict["reference_url"]["value"]
         ref_url_prop = ref_dict["reference_url"]["prop"]
         ref_url_claim = self.wdstuff.make_simple_claim(
             ref_url_prop, ref_url)
         ref = self.wdstuff.Reference(
             source_test=[source_claim, ref_url_claim],
             source_notest=self.wdstuff.make_simple_claim(
                 prop_date, date_item))
     else:
         ref = self.wdstuff.Reference(
             source_test=[source_claim],
             source_notest=self.wdstuff.make_simple_claim(
                 prop_date, date_item))
     return ref
示例#13
0
def addDateClaim(repo='', item='', claim='', date='', lang=''):
    if repo and item and claim and date and lang:
        claim = pywikibot.Claim(repo, claim)
        if len(date.split('-')) == 3:
            claim.setTarget(
                pywikibot.WbTime(year=date.split('-')[0],
                                 month=date.split('-')[1],
                                 day=date.split('-')[2]))
        elif len(date.split('-')) == 2:
            claim.setTarget(
                pywikibot.WbTime(year=date.split('-')[0],
                                 month=date.split('-')[1]))
        elif len(date.split('-')) == 1:
            claim.setTarget(pywikibot.WbTime(year=date.split('-')[0]))
        item.addClaim(claim, summary='BOT - Adding 1 claim')
        addImportedFrom(repo=repo, claim=claim, lang=lang)
示例#14
0
def mainloop():
    limit = None
    entities = sorted(const.PROPERTY_IDS.keys())

    for arg in wp.handle_args():
        if arg.startswith('-limit'):
            limit = int(arg[len('-limit:'):])
        elif arg.startswith("-entities"):
            entities = arg[len("-entities:"):].split(",")

    const.MUSICBRAINZ_CLAIM.setTarget(const.MUSICBRAINZ_WIKIDATAPAGE)
    today = datetime.datetime.today()
    date = wp.WbTime(year=today.year, month=today.month, day=today.day)
    const.RETRIEVED_CLAIM.setTarget(date)
    setup_db()

    for entitytype in entities:
        processed_table_query = create_processed_table_query(entitytype)
        create_table(processed_table_query)

    bot = Bot()

    while True:
        const.WIKIDATA.login()
        for entitytype in entities:
            entity_type_loop(bot, entitytype, limit)
        bot.update_rate_limits()
        sleep(settings.sleep_time_in_seconds)
示例#15
0
    def setUp(self):
        """Add a claim with two qualifiers."""
        super().setUp()
        testsite = self.get_repo()
        item = pywikibot.ItemPage(testsite, 'Q68')
        item.get()
        # Create claim with qualifier
        if 'P115' in item.claims:
            item.removeClaims(item.claims['P115'])

        claim = pywikibot.page.Claim(testsite,
                                     'P115',
                                     datatype='wikibase-item')
        target = pywikibot.ItemPage(testsite, 'Q271')
        claim.setTarget(target)
        item.addClaim(claim)

        item.get(force=True)

        qual_1 = pywikibot.page.Claim(testsite, 'P88', is_qualifier=True)
        qual_1.setTarget(pywikibot.WbTime(year=2012))
        item.claims['P115'][0].addQualifier(qual_1)

        qual_2 = pywikibot.page.Claim(testsite, 'P580', is_qualifier=True)
        qual_2.setTarget(pywikibot.ItemPage(testsite, 'Q67'))
        item.claims['P115'][0].addQualifier(qual_2)
def create_claim(property=None,
                 value=None,
                 item=None,
                 quantity=None,
                 repo=REPO,
                 site=SITE,
                 year=None,
                 month=None,
                 day=None,
                 text=None,
                 language=None):

    claim = pywikibot.Claim(repo, property)

    if item is not None:
        value = pywikibot.ItemPage(repo, item)
    elif quantity is not None:
        value = pywikibot.WbQuantity(quantity, site=site)
    elif year is not None:
        value = pywikibot.WbTime(year=year, month=month, day=day)
    elif text is not None:
        if language is not None:
            value = pywikibot.WbMonolingualText(text, language)

    claim.setTarget(value)

    return claim
 def compare_dates(self):
     this_date1=pywikibot.WbTime(site=site,year=2008, month=1, day=1, precision='day')    
     this_date2=pywikibot.WbTime(site=site,year=2008, month=1, day=2, precision='day')    
     this_date3=pywikibot.WbTime(site=site,year=2008, month=2, day=1, precision='day')    
     this_date4=pywikibot.WbTime(site=site,year=2008, month=12, day=31, precision='day') 
     this_date5=pywikibot.WbTime(site=site,year=2009, month=1, day=1, precision='day')    
     self.assertEqual(compare_dates(this_date1,this_date1),0)
     self.assertEqual(compare_dates(this_date4,this_date4),0)
     self.assertEqual(compare_dates(this_date2,this_date1),1)
     self.assertEqual(compare_dates(this_date1,this_date2),2)
     self.assertEqual(compare_dates(this_date3,this_date1),1)
     self.assertEqual(compare_dates(this_date1,this_date3),2)
     self.assertEqual(compare_dates(this_date4,this_date1),1)
     self.assertEqual(compare_dates(this_date1,this_date4),2)
     self.assertEqual(compare_dates(this_date5,this_date4),1)
     self.assertEqual(compare_dates(this_date4,this_date5),2)
示例#18
0
def setStatement(item, repo, genID, genUrl):
    claims = item.get('claims')
    #ref
    today = date.today()
    statedin = pywikibot.Claim(repo, u'P248')
    itis = pywikibot.ItemPage(repo, "Q65660713")
    statedin.setTarget(itis)

    retrieved = pywikibot.Claim(repo, u'P813')
    dateCre = pywikibot.WbTime(year=int(today.strftime("%Y")), month=int(today.strftime("%m")), day=int(today.strftime("%d")))
    retrieved.setTarget(dateCre)

    if u'P2373' in claims[u'claims']:
        pywikibot.output(u'Error: Already have Genius artist ID!')
    else:
        stringclaim = pywikibot.Claim(repo, u'P2373')
        stringclaim.setTarget(str(genUrl))
        item.addClaim(stringclaim, summary=u'Adding Genius artist ID')

        stringclaim.addSources([statedin, retrieved], summary=u'Adding sources to Genius artist ID.')
        print("Added Genius artist ID")
        
    if u'P6351' in claims[u'claims']:
            pywikibot.output(u'Error: Already have Genius artist numeric ID!')
    else:
        stringclaim2 = pywikibot.Claim(repo, u'P6351')
        stringclaim2.setTarget(str(genID))
        item.addClaim(stringclaim2, summary=u'Adding Genius artist numeric ID (P6351)')
        
        stringclaim2.addSources([statedin, retrieved], summary=u'Adding sources to Genius artist numeric ID.')
        print("Added Genius artist numeric ID")
示例#19
0
 def make_pywikibot_item(self, value):
     val_item = None
     if isinstance(value, list) and len(value) == 1:
         value = value[0]
     if utils.string_is_q_item(value):
         val_item = self.make_q_item(value)
     elif value == "novalue":
         val_item = value
     elif isinstance(value, dict) and 'monolingual_value' in value:
         text = value['monolingual_value']
         language = value['lang']
         val_item = pywikibot.WbMonolingualText(text=text,
                                                language=language)
     elif isinstance(value, dict) and 'quantity_value' in value:
         number = value['quantity_value']
         if 'unit' in value:
             unit = self.wdstuff.QtoItemPage(value["unit"])
         else:
             unit = None
         val_item = pywikibot.WbQuantity(amount=number,
                                         unit=unit,
                                         site=self.repo)
     elif isinstance(value, dict) and 'date_value' in value:
         date_dict = value["date_value"]
         val_item = pywikibot.WbTime(year=date_dict.get("year"),
                                     month=date_dict.get("month"),
                                     day=date_dict.get("day"))
     elif value == "novalue":
         #  raise NotImplementedError
         #  implement Error
         print("Status: novalue will be added here")
     else:
         val_item = value
     return val_item
示例#20
0
 def test_set_incorrect_target_value(self):
     wikidata = self.get_repo()
     claim = pywikibot.Claim(wikidata, 'P569')
     self.assertRaises(ValueError, claim.setTarget, 'foo')
     claim = pywikibot.Claim(wikidata, 'P856')
     self.assertRaises(ValueError, claim.setTarget,
                       pywikibot.WbTime(2001, site=wikidata))
示例#21
0
  def __init__(self):
    self.site = pywikibot.Site("wikidata", "wikidata")
    self.repo = self.site.data_repository()

    time_str = datetime.datetime.now().isoformat("-")[:19].replace(":","-")
    if flags.arg.test:
      record_file_name = "local/data/e/wikibot/test-birth-dates.rec"
      time_str = "test-" + time_str
    else:
      record_file_name = "local/data/e/wikibot/birth-dates.rec"
    status_file_name = "local/logs/wikibotlog-" + time_str + ".rec"
    self.record_file = sling.RecordReader(record_file_name)
    self.status_file = sling.RecordWriter(status_file_name)

    self.store = sling.Store()
    self.n_item = self.store["item"]
    self.n_facts = self.store["facts"]
    self.n_provenance = self.store["provenance"]
    self.n_category = self.store["category"]
    self.n_method = self.store["method"]
    self.n_status = self.store["status"]
    self.n_revision = self.store["revision"]
    self.n_url = self.store["url"]
    self.n_skipped = self.store["skipped"]
    self.store.freeze()
    self.rs = sling.Store(self.store)

    self.source_claim = pywikibot.Claim(self.repo, "P3452") # inferred from
    self.time_claim = pywikibot.Claim(self.repo, "P813") # referenced (on)
    today = datetime.date.today()
    time_target = pywikibot.WbTime(year=today.year,
                                   month=today.month,
                                   day=today.day)
    self.time_claim.setTarget(time_target)
示例#22
0
 def test_set_date(self):
     claim = pywikibot.Claim(wikidata, 'P569')
     self.assertEquals(claim.type, 'time')
     claim.setTarget(pywikibot.WbTime(year=2001, month=01, day=01))
     self.assertEquals(claim.target.year, 2001)
     self.assertEquals(claim.target.month, 1)
     self.assertEquals(claim.target.day, 1)
示例#23
0
    def getDate(self, datestring):
        if len(datestring) == 4:
            newdate = pywikibot.WbTime(year=int(datestring))
            return newdate

        dateList = datestring.split(u'-')

        if len(dateList) == 2:
            newdate = pywikibot.WbTime(year=int(dateList[0]),
                                       month=int(dateList[1]))
            return newdate
        elif len(dateList) == 3:
            newdate = pywikibot.WbTime(year=int(dateList[0]),
                                       month=int(dateList[1]),
                                       day=int(dateList[2]))
            return newdate
        """  
示例#24
0
 def test_set_date(self):
     wikidata = self.get_repo()
     claim = pywikibot.Claim(wikidata, 'P569')
     self.assertEqual(claim.type, 'time')
     claim.setTarget(pywikibot.WbTime(year=2001, month=1, day=1, site=wikidata))
     self.assertEqual(claim.target.year, 2001)
     self.assertEqual(claim.target.month, 1)
     self.assertEqual(claim.target.day, 1)
 def test_invalid_qualifiers(self):
     """Test ItemClaimFilterPageGenerator on sample page using invalid qualifiers."""
     qualifiers = {
         'P580': 1950,
         'P582': pywikibot.WbTime(1960, 1, 1, precision=9, site=self.site),
     }
     self._simple_claim_test('P463', self._get_council_page(), qualifiers,
                             False)
示例#26
0
def update_existing_or_create_new_claim_date(repo, item, existing_claims, property_id, target_year, target_month, target_day):
	target_precision = 'day'
	if target_month is None and target_day is None:
		target_precision = 'year'
	elif target_day is None:
		target_precision = 'month'
	value = pywikibot.WbTime(year=target_year, month=target_month, day=target_day, precision=target_precision)
	update_existing_or_create_new_claim(repo, item, existing_claims, property_id, value)
示例#27
0
 def _get_wbtime(self, year):
     if len(year) == 4:
         return pywikibot.WbTime(
             year=int(year),
             calendarmodel='http://www.wikidata.org/entity/Q1985727')
     if len(year) == 6:
         return pywikibot.WbTime(
             year=int(year[0:4]),
             month=int(year[4:6]),
             calendarmodel='http://www.wikidata.org/entity/Q1985727')
     if len(year) == 8:
         return pywikibot.WbTime(
             year=int(year[0:4]),
             month=int(year[4:6]),
             day=int(year[6:8]),
             calendarmodel='http://www.wikidata.org/entity/Q1985727')
     return None
    def test_has_claim_match_WbTime_type(self):
        prop = 'P74'
        itis = pywikibot.WbTime(year=2016, month=11, day=22, site=self.repo)
        function = 'wikidataStuff.WikidataStuff.WikidataStuff.compareWbTimeClaim'

        with mock.patch(function, autospec=True) as mock_compare_WbTime:
            self.wd_stuff.has_claim(prop, itis, self.wd_page)
            mock_compare_WbTime.assert_called_once_with(
                self.wd_stuff, itis, itis)
示例#29
0
	def set_claim(numToInput):
		claim = pywikibot.Claim(repo, property)
		claim.setTarget(pywikibot.WbQuantity(numToInput, site=repo))
		item.addClaim(claim, bot=True)
		#this link should be CBS source table link
		add_source_url(claim, data[x]["srcurl"])
		#date should be the date that is specified for last updated CBS data date
		add_point_in_time(claim, pywikibot.WbTime(year = data[x]["srcDate"]))
		return claim
    def today(self):
        """Return a wikibase time object with current date."""

        now = self.repo.server_time()
        return pywikibot.WbTime(
            year=now.year,
            month=now.month,
            day=now.day,
            calendarmodel="http://www.wikidata.org/entity/Q1985727")