"""
29.Holen Sie sich die URL des Flaggenbildes
Verwenden Sie den Inhalt der Vorlage, um die URL des Flaggenbilds abzurufen. (Hinweis:Rufen Sie imageinfo der MediaWiki-API auf, um den Dateiverweis in eine URL zu konvertieren.
"""
import json
import re
import urllib.parse
import urllib.request
import requests
import utils
def get_uk_text(path):
with open(path) as f:
for line in f:
line_data = json.loads(line)
if line_data["title"] == "England":
data = line_data
break
return data["text"]
def get_basic_info(string: str) -> str:
"""Get basic information section
"""
pattern = re.compile(
r"""
^\{\{Grundinformation.*?$ # '{{Grundinformation'Zeilen beginnend mit
(.*?) #Erfassen Sie ein Ziel, 0 oder mehr Zeichen, nicht gierig
^\}\}$ # '}}'Zeilen, die mit enden
""",
re.MULTILINE | re.DOTALL | re.VERBOSE,
)
return re.findall(pattern, string)[0]
def get_content(string: str) -> list:
r"""
https://docs.python.org/3/library/re.html#regular-expression-syntax
RE:
- re.X (re.VERBOSE) Allow us add command to explain the regular expression
- re.M (re.MULTILINE) Apply match to each line. If not specified, only match the first line.
- re.S (re.DOTALL) Allow to recognize '\n'
- [] Used to indicate a set of characters. [(+*)] will match any of the literal characters '(', '+', '*', or ')'.
- ^\| String begin with |
- ? Causes the resulting RE to match 0 or 1 repetitions
- *? The '*' qualifier is greedy.
Adding ? after the qualifier makes it perform the match in non-greedy or minimal fashion; as few characters as possible will be matched.
e.g. <.*> is matched against '<a> b <c>'
e.g. <.*?> will match only '<a>'
- (...) Matches whatever regular expression is inside the parentheses,
- (?=...) Matches if ... matches next, but doesn’t consume any of the string. This is called a lookahead assertion.
For example, Isaac (?=Asimov) will match 'Isaac ' only if it’s followed by 'Asimov'.
- (?:...) A non-capturing version of regular parentheses.
Input:
- '|Nationaler Emblem-Link=([[Britisches nationales Emblem|Staatswappen]])'
Return:
- {'Nationaler Emblem-Link': '([[Britisches nationales Emblem|Staatswappen]])'}
"""
pattern = re.compile(
r"""
^\| # '|'Zeilen beginnend mit
(.+?) #Erfassen Sie das Ziel (Feldname), ein oder mehrere Zeichen, nicht gierig
\s* #0 oder mehr Leerzeichen
=
\s* #0 oder mehr Leerzeichen
(.+?) #Erfassen Sie ein Ziel (Wert), ein oder mehrere Zeichen, die nicht gierig sind
(?: #Starten Sie eine Gruppe, die nicht erfasst wird
(?=\n\|) #Neue Zeile+'|'Vorher (positive Vorausschau)
| #Oder
(?=\n$) #Neue Zeile+Vor dem Ende (bejahender Ausblick)
) #Gruppenende
""",
re.MULTILINE | re.DOTALL | re.VERBOSE,
)
result = re.findall(pattern, string)
return {k: v for k, v in result} # dict is ordered when using python 3.7
def remove_markup(target: str) -> str:
# ans26: remvoe highlight markup
"""
「'''Großbritannien'''」->「Großbritannien」
"""
pattern = re.compile(
r"""
(\'{2,5}) #2-5'(Beginn des Markups)
(.*?) #Ein oder mehrere Zeichen (Zielzeichenfolge)
(\1) #Entspricht der ersten Aufnahme (Ende des Markups)
""",
re.MULTILINE | re.VERBOSE,
)
target = pattern.sub(r"\2", target) #Schalten Sie die zweite Gruppe auf Ganz
"""
and27: remove internal link and file
[[London]] -> London
[[britischer Premierminister|Premierminister]] -> Premierminister
[[Datei:Royal Coat of Arms of the United Kingdom.svg|85px|Britisches nationales Emblem]] -> Britisches nationales Emblem
"""
pattern = re.compile(
r"""
\[\[ # '[['(Beginn des Markups)
(?: #Starten Sie eine Gruppe, die nicht erfasst wird
[^|]*? # '|'0 oder mehr Zeichen als nicht gierig
\| # '|'
)*? #Gruppe ist 0 oder mehr, nicht gierig
([^|]*?) #Ziel erfassen,'|'Andere als 0 Zeichen, nicht gierig (anzuzeigende Zeichenfolge)
\]\] # ']]'(Ende des Markups)
""",
re.MULTILINE | re.VERBOSE,
)
target = pattern.sub(r"\1", target) #Schalten Sie die erste Gruppe auf Ganz
# ans28: remove markups as many as possible
# Remove {{}}
"""
{{lang|fr|Dieu et mon droit}} -> Dieu et mon droit
{{Temporäre Verbindung|Lindsay Foil|en|Lindsay Hoyle}} -> Lindsay Hoyle
"""
pattern = re.compile(
r"""
\{\{ # '{{'(Beginn des Markups)
.*? #0 oder mehr Zeichen, nicht gierig
(?:
[^|]*?
\|
)*?
([^|]*?)
\}\} # '}}'(Ende des Markups)
""",
re.MULTILINE | re.VERBOSE,
)
target = pattern.sub(r"\1", target)
# Remove <ref> pattern 1
"""
"66.435.600<ref>{{Cite web|url=https://www.ons.gov.uk/peoplepopulationandcommunity/populationandmigration/populationestimates|title=Population estimates - Office for National Statistics|accessdate=2019-06-26|date=2019-06-26}}</ref>",
->
"66.435.600",
"""
pattern = re.compile(r"<ref.*?</ref>")
target = pattern.sub(r"", target)
# Remove <ref> pattern 2
"""
('2.316,2 Milliarden<ref name="imf-statistics-gdp" />', "2.316,2 Milliarden"),
"""
pattern = re.compile(
r"""
< # '<'(Beginn des Markups)
\/? # '/'Erscheint 0 oder 1 (im Fall des End-Tags/Es gibt)
ref # 'ref'
[^>]*? # '>'Andere als 0 Zeichen, nicht gierig
> # '>'(Ende des Markups)
""",
re.MULTILINE + re.VERBOSE,
)
target = pattern.sub(r"", target) # no space
# Replace <br> with ' ',Die Nationalhymne ist leichter zu lesen
"""
"God Save the Queen}}{{en icon}}<br />Gott, beschütze die Königin<br />{{center|Datei:United States Navy Band - God Save the Queen.ogg}}"
->
"God Save the Queen}}en icon Schütze die Königin, Gottesakte:United States Navy Band - God Save the Queen.ogg",
"""
pattern = re.compile(
r"""
< # '<'(Beginn des Markups)
\/? # '/'Erscheint 0 oder 1 (im Fall des End-Tags/Es gibt)
br # 'br'
[^>]*? # '>'Andere als 0 Zeichen, nicht gierig
> # '>'(Ende des Markups)
""",
re.MULTILINE + re.VERBOSE,
)
target = pattern.sub(r" ", target) # with space
# # Premove <br>, <ref> pattern 2
# """
# ("Etabliert<br />(Gemeinsames Gesetz von 1707)", "Etabliert(Gemeinsames Gesetz von 1707)"),
# ('2.316,2 Milliarden<ref name="imf-statistics-gdp" />', "2.316,2 Milliarden"),
# """
# pattern = re.compile(
# r"""
# < # '<'(Beginn des Markups)
# \/? # '/'Erscheint 0 oder 1 (im Fall des End-Tags/Es gibt)
# [br|ref] # 'br'Oder'ref'
# [^>]*? # '>'Andere als 0 Zeichen, nicht gierig
# > # '>'(Ende des Markups)
# """,
# re.MULTILINE + re.VERBOSE,
# )
# target = pattern.sub(r"", target)
# Remove external link [http://xxxx] 、[http://xxx xxx]
"""
[http://www.example.org] -> ''
[http://www.example.org Anzeigezeichen] -> 'Zeichen anzeigen'
"""
pattern = re.compile(
r"""
\[http.?:\/\/ # '[http://'(Start des Markups) oder https
(?: #Starten Sie eine Gruppe, die nicht erfasst wird
[^\s]*? #0 oder mehr nicht leere Zeichen, nicht gierig
\s #Leer
)? #Gruppenende, diese Gruppe erscheint 0 oder 1
([^]]*?) #Ziel erfassen,']'Andere als 0 Zeichen, nicht gierig (anzuzeigende Zeichenfolge)
\] # ']'(Ende des Markups)
""",
re.MULTILINE + re.VERBOSE,
)
target = pattern.sub(r"\1", target)
return target
def get_flag_url(query: str) -> str:
# Send request to MediaWiki
request = urllib.request.Request(query, headers={"User-Agent": "Xu"})
connection = urllib.request.urlopen(request)
# get json data
data = json.loads(connection.read().decode())
utils.save_json(data, "29_wiki_api.json")
# get URL
url = data["query"]["pages"].popitem()[1]["imageinfo"][0]["url"]
return url
def get_flag_url_with_requests(query: str) -> str:
data = requests.get(query)
return re.search(r'"url":"(.+?)"', data.text).group[1]
# and20
uk_text = get_uk_text("jawiki-country.json") # See uk_text.txt
# ans25
basic_info = get_basic_info(uk_text)
fields = get_content(basic_info) # See 25_en_basic_info.json
# ans26, ans27, ans28
result = {k: remove_markup(v) for k, v in fields.items()} # See 26_no_markup.json
# ans29
flag_name = result["Flaggenbild"]
query = (
"https://www.mediawiki.org/w/api.php?"
+ "action=query"
+ "&titles=File:"
+ urllib.parse.quote(flag_name)
+ "&format=json"
+ "&prop=imageinfo"
+ "&iiprop=url"
)
url1 = get_flag_url(query)
url2 = get_flag_url_with_requests(query)
print(url1)
assert url1 == url2
Recommended Posts