"""
25.Template extraction
Extract the field names and values of the "basic information" template included in the article and store them as a dictionary object.
"""
import json
import re
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"]
uk_text = get_uk_text("jawiki-country.json")
# See uk_text.txt
# ans24
def get_basic_info(string: str) -> str:
"""Get basic information section
"""
pattern = re.compile(
r"""
^\{\{Basic information.*?$ # '{{Basic information'Lines starting with
(.*?) #Capture target, any 0 or more characters, non-greedy
^\}\}$ # '}}'Lines ending with
""",
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'
- ^\| 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:
- '|National emblem link=([[British coat of arms|National emblem]])'
Return:
- {"National emblem link": "([[British coat of arms|National emblem]])"}
"""
pattern = re.compile(
r"""
^\| # '|'Lines starting with
(.+?) #Capture target (field name), any one or more characters, non-greedy
\s* #0 or more whitespace characters
=
\s* #0 or more whitespace characters
(.+?) #Capture target (value), any one or more characters, non-greedy
(?: #Start a group that is not captured
(?=\n\|) #new line+'|'Before (Affirmative look-ahead)
| #Or
(?=\n$) #new line+Before the end (affirmative look-ahead)
) #Group end
""",
re.MULTILINE | re.DOTALL | re.VERBOSE,
)
result = re.findall(pattern, string)
return {k: v for k, v in result} # dict is ordered due to python 3.7
basic_info = get_basic_info(uk_text)
# print(basic_info[-100:])
# |International call number= 44
# |Note= <references/>
result = get_content(basic_info)
utils.save_json(result, "25_en_basic_info.json")
for r in result.items():
print(r)
# ('Abbreviated name', 'England')
# ('Japanese country name', 'United Kingdom of Great Britain and Northern Ireland')
# ...
# ('International call number', '44')
# ('Note', '<references/>')
Recommended Posts