Я использую API Википедии, чтобы очистить норвежский контент, очистить его и записать в файл для использования при обучении языковой модели для CMU Sphinx.
При запуске .random-function в цикле for, но я получаю проблему, хотя.Я подсчитываю количество уникальных страниц через pageId и получаю большое количество дубликатов.В начале это не слишком много, но через некоторое время количество дубликатов удваивает количество уникальных идентификаторов.Когда мы получили 40 страниц, у нас есть около 80 дубликатов.
Конечно, есть что-то в функции .random, которую мы не видим?
Вот код.RegEx имеет функции для более удобного чтения порядка фильтров.
import re
import wikipedia
"""
Module wikitest.py - Script for scraping Wikipedia of text based on articles
found by using wikipedia.random.
Used for gathering and formatting written text representative of the
Norwegian language,
for use in training language models.
"""
# Create regex to filter the results
specialcharreg = re.compile(r'[^A-Za-zÆØÅæøå0-9.,-]+', re.IGNORECASE)
whitespacereg = re.compile(r' {2}', re.IGNORECASE)
punctuationreg = re.compile(r'[.]+', re.IGNORECASE)
shortsentencereg = re.compile(r'(</?s>)([a-zæøåA-ZÆØÅ0-9,\- ]{0,50})(</?
s>)', re.IGNORECASE)
isbnreg = re.compile(r'(ISBN)([0-9- ]{7,21})', re.IGNORECASE)
nospaceaftertagreg = re.compile(r'(<s>([a-zæøåA-ZÆØÅ,-]))', re.IGNORECASE)
# filter-methods for formatting the text
def nospeacialchar(wikicontent): return re.sub(specialcharreg, ' ',
wikicontent)
def nodoublewhitespace(wikicontent): return re.sub(whitespacereg, ' ',
wikicontent)
def faultysentence(wikicontent): return re.sub(shortsentencereg, '',
wikicontent)
def inserttags(wikicontent): return re.sub(punctuationreg, ' </s>\n<s>', wikicontent)
def noemptylines(wikicontent): return "".join([s for s in wikicontent.splitlines(True) if s.strip("\r\n")])
def noisbn(wikicontent): return re.sub(isbnreg, '', wikicontent)
def nospaceaftertag(wikicontent): return re.sub(nospaceaftertagreg, '<s> ', wikicontent)
# We only want articles written in Norwegian
wikipedia.set_lang("no")
# initialize different counters for counting duplicates and uniques
idlist = []
duplicatecount = 0
uniquecount: int = 0
showuniquecount = 0
# define number of pages to get
for x in range(0, 10001):
try:
randompages = wikipedia.random(1)
for page in randompages:
# get wikipedia page
wikipage = wikipedia.page(page)
# get page ID
pageid = wikipage.pageid
# check for ID-duplicate
if pageid not in idlist:
# add ID to list of gotten pages
idlist.append(pageid)
uniquecount += 1
showuniquecount += 1
# on every tenth iteration, print current unique count
if showuniquecount == 10:
print("Current unique page count:{0}".format(uniquecount))
showuniquecount = 0
wikicontent = wikipage.content
# filter the content using different regex-functions
filteredcontent = \
faultysentence(
noemptylines(
nospaceaftertag(
faultysentence(
inserttags(
nodoublewhitespace(
noisbn(
nospeacialchar(
wikicontent))))))))
print(filteredcontent)
# Write operation to file
with open("wikiscraping2.txt", "a", encoding="utf-8") as the_file:
the_file.write('<s> ' + filteredcontent)
the_file.close()
else:
duplicatecount += 1
print("Duplicate! Current duplicate count:{0}".format(duplicatecount))
# catch exception of wikipedia not knowing which page is specified
except wikipedia.DisambiguationError as e:
print('DisambiguationError!')
# continue to next
continue
# catch exception
except wikipedia.exceptions.PageError as d:
print('Index error! (Page could not be found)')
# continue to next
continue