Parsing returns from AltLabel in a SPARQL query

只愿长相守 提交于 2019-12-11 02:35:25

问题


In a Wikidata SPARQL query such as the following, I want to be able to use a custom delimiter for the returns for ?placeOfBirthAltLabel.

The problem is that some values under ?placeOfBirthAltLabel contain commas

e.g. synonyms for "New York" include "New York, USA" as a single entry.

However, as the returns are comma delimited, this single entry will be parsed as two separate strings.

So in other words I need the return to be [New York, USA ; NYC ; NYC, USA ] as opposed to [New York, USA, NYC, NYC, USA]

SELECT ?item ?itemLabel ?placeOfBirthLabel ?placeOfBirthAltLabel 
WHERE
{
  ?item wdt:P106 wd:Q10833314.
  OPTIONAL { ?item wdt:P19 ?placeOfBirth }

  SERVICE wikibase:label { bd:serviceParam wikibase:language "en" }
}

LIMIT 100

Thanks!


回答1:


You do not need to parse alternative labels. Their values are concatenated by the label service. Just do not use the label service for alternative labels:

SELECT ?item ?itemLabel ?placeLabel ?place_alt_label WHERE { 
    ?item wdt:P106 wd:Q10833314. 
    OPTIONAL { 
        ?item wdt:P19 ?place .
        OPTIONAL {
            ?place skos:altLabel ?place_alt_label .
            FILTER (lang(?place_alt_label)='en')
            }
    }  
    SERVICE wikibase:label { bd:serviceParam wikibase:language "en" }
}

Try it!

If you still want to parse... The comma is hardcoded, use grouping and GROUP_CONCAT with custom separator instead:

SELECT ?item ?itemLabel ?placeLabel
    (GROUP_CONCAT(?place_alt_label; separator='; ') AS ?4) WHERE { 
    ?item wdt:P106 wd:Q10833314. 
    OPTIONAL { 
        ?item wdt:P19 ?place .
        OPTIONAL {
            ?place skos:altLabel ?place_alt_label .
            FILTER (lang(?place_alt_label)='en')
            }
    }  
    SERVICE wikibase:label { bd:serviceParam wikibase:language "en" }
}
GROUP BY ?item ?itemLabel ?placeLabel

Try it!


Be carefull with variables projected by the label service. For example,

SELECT ?item ?itemLabel ?placeLabel   {...}
GROUP BY ?item ?itemLabel ?placeLabel

should work, whereas

SELECT ?item ?itemLabel (SAMPLE(?placeLabel) AS ?3)   {...}
GROUP BY ?item ?itemLabel

shouldn't.



来源:https://stackoverflow.com/questions/51520591/parsing-returns-from-altlabel-in-a-sparql-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!