Python wikipedia 模块,set_lang() 实例源码

我们从Python开源项目中,提取了以下13个代码示例,用于说明如何使用wikipedia.set_lang()

项目:chalice-linebot    作者:c-bata    | 项目源码 | 文件源码
def wikipedia_search(word):
    """Search a word meaning on wikipedia."""
    wikipedia.set_lang('ja')
    results = wikipedia.search(word)

    # get first result
    if results:
        page = wikipedia.page(results[0])
        msg = page.title + "\n" + page.url
    else:
        msg = '`{}` ??????????????'.format(word)
    return msg


# ====================================
# Google News
# ====================================
项目:Mash-Cogs    作者:Canule    | 项目源码 | 文件源码
def wikipedia(self, ctx, *text):
        """Wikipedia search."""     

        if text == ():
            await send_cmd_help(ctx)
            return
        else:            
            s = "_";
            search = ""
            search = s.join(text)
            user = ctx.message.author
            wikiLang = 'en'# Define the Wikipedia language / Most of these are supported » https://nl.wikipedia.org/wiki/ISO_3166-1
            ws = None
            wikipedia.set_lang(wikiLang)# Set the Wikipedia language.
            try:
                ws = wikipedia.page(search)
                wikiUrl = (ws.url.encode('ascii', 'xmlcharrefreplace'))
                await self.bot.say(wikiUrl.decode("utf8"))
            except:
                await self.bot.say( 'Sorry {}, no wiki hit, try to rephrase'.format(user))
项目:cdata    作者:cnschema    | 项目源码 | 文件源码
def wikipedia_search_slow(query, lang="en", max_result=1):
    import wikipedia
    #wikification
    query = any2unicode(query)
    items = []
    ret = {"query":query, "itemList":items}
    wikipedia.set_lang(lang)
    wikiterm = wikipedia.search(query)
    #logging.info(wikiterm)
    for idx, term in enumerate(wikiterm[0:max_result]):
        wikipage = wikipedia.page(term)
        item = {
            "name": wikipage.title,
            "description": wikipedia.summary(term, sentences=1),
            "url": wikipage.url,
        }
        items.append(item)

    return ret
项目:eatradish_haoyebot    作者:eatradish    | 项目源码 | 文件源码
def wikipedia_summary(msg, lang = 'en'):
    try:
        if lang == 'en':
            wikipedia.set_lang('en')
        else:
            wikipedia.set_lang(lang)
        url = wikipedia.page(msg).url
        msg = wikipedia.summary(msg)
        fliter = []
        for i in msg:
            if i != '\n':
                fliter.append(i)
            else:
                break
        msg = "".join(fliter)
        return msg + '\n' + url
    except:
        return "Not Found Page or LANG"
项目:Abb1t    作者:k-freeman    | 项目源码 | 文件源码
def __init__(self, bot):
        self.bot = bot.bot
        self.description = "*/wiki* _<term>_ - defines _<term>_ using wikipedia"
        self.queue_in = Queue()
        wikipedia.set_lang("de")
        thread.start_new_thread(self.run, ())

        #self.lastsearch_dict = {} #this may be implemented in order to enter simply a number
        # based on the "this was too inspecific" message. not done yet.
项目:LDA-REST    作者:valentinarho    | 项目源码 | 文件源码
def download_single(wiki_page_name, only_summary=False, language='en'):
    """
    Download the content of a wikipedia page

    :param wiki_page_name: the name
    :param only_summary:
    :return:
    """

    wikipedia.set_lang(language)
    if only_summary:
        page = wikipedia.page(wiki_page_name)
        return page.content
    else:
        return wikipedia.summary(wiki_page_name)
项目:sarah    作者:semicode-ltd    | 项目源码 | 文件源码
def do_activate(self, args, argv):
        wikipedia.set_lang("de")
        print(wikipedia.summary(' '.join(args), sentences=2))
项目:pyconjpbot    作者:pyconjp    | 项目源码 | 文件源码
def wikipedia_page(message, option, query):
    """
    Wikipedia??????????
    """
    if query == 'help':
        return

    # set language
    lang = 'ja'
    if option:
        _, lang = option.split('-')
    wikipedia.set_lang(lang)

    try:
        # search with query
        results = wikipedia.search(query)
    except:
        botsend(message, '??????? `{}` ???????'.format(lang))
        return

    # get first result
    if results:
        page = wikipedia.page(results[0])

        attachments = [{
            'fallback': 'Wikipedia: {}'.format(page.title),
            'pretext': 'Wikipedia: <{}|{}>'.format(page.url, page.title),
            'text': page.summary,
        }]
        botwebapi(message, attachments)
    else:
        botsend(message, '`{}` ??????????????'.format(query))
项目:TwentyTwo    作者:EPITECH-2022    | 项目源码 | 文件源码
def wikipedia(self, context, lang: str = None, query: str = None):
        ''' Get a page from wikipedia and reply with an embed '''
        query = self.bot.get_text(context)
        if lang is not None:
            if lang.startswith('(') and lang.endswith(')'):
                query = query[len(lang) + 1:]
                lang = lang[1:-1]
            else:
                lang = None
        if query in [None, '', ' ']:
            await self.bot.doubt(context)
            return
        try:
            import wikipedia
            if lang is not None and lang in wikipedia.languages().keys():
                wikipedia.set_lang(lang)
            else:
                wikipedia.set_lang('en')
            page    = wikipedia.page(query)
            summary = page.summary
            if len(summary) > 1222: # totally arbitrary chosen number
                summary = summary[:1220] + '...'
            embed   = discord.Embed(title=page.title, description=summary, url=page.url)
            embed.set_footer(text=page.url)
            if self.bot.config['bleeding']:
                if len(page.images) > 0:
                    embed.set_image(url=page.images[0])
            await self.bot.say(embed=embed)
            await self.bot.replied(context)
        except wikipedia.PageError as e:
            await self.bot.reply('{}\nMake sure you search for page titles in the language that you have set.'.format(e))
            await self.bot.doubt(context)
        except KeyError:
            pass
        except wikipedia.DisambiguationError as e:
            msg = '```\n{}\n```'.format(e)
            await self.bot.doubt(context)
            await self.bot.say(msg)
项目:Onyx    作者:OnyxProject    | 项目源码 | 文件源码
def get_article(self):
        try:
            wikipedia.set_lang(self.lang)
            article = wikipedia.page(self.search)
            return article
        except Exception as e:
            logger.error('Getting wiki article error : ' + str(e))
            raise WikiException(str(e))
项目:Onyx    作者:OnyxProject    | 项目源码 | 文件源码
def get_summary(self):
        try:
            wikipedia.set_lang(self.lang)
            summary = wikipedia.summary(self.search)
            return summary
        except:
            logger.error('Getting wiki summary error : ' + str(e))
            raise WikiException(str(e))
项目:tulen    作者:detorto    | 项目源码 | 文件源码
def get_wiki_page(req):
        wikipedia.set_lang("ru")
        p = wikipedia.page(req)
        return p
项目:copaspedia    作者:selesdepselesnul    | 项目源码 | 文件源码
def _extract_from_wiki(self):
        title = self.title_line_edit.text()
        if title:
            page = self.page_combo_box.currentText()
            wikipedia.set_lang(self.lang_combo_box.currentText())
            self.load_progressbar.setMinimum(0)
            self.load_progressbar.setMaximum(0)

            class ProgressThread(QThread, QWidget):

                content_link_arrived = pyqtSignal([list])
                content_text_arrived = pyqtSignal(['QString'])
                content_image_arrived = pyqtSignal([list, 'QString'])
                error_occurred = pyqtSignal()
                valid_images = []

                def run(self):
                    try:
                        wiki = wikipedia.page(title=title)
                        f = open('templates/template.html')
                        if page == 'Content':
                            self.content_text_arrived.emit(wiki.content)
                        elif page == 'Images':

                            print(wiki.images)

                            self.des_dir = Preferences.output_path + '/' + title 
                            self.valid_images = []
                            if not os.path.exists(self.des_dir):
                                print(self.des_dir)
                                os.mkdir(self.des_dir)   

                            for i in wiki.images:
                                if PurePath(i).suffix in Preferences.valid_image_formats:
                                    print(i)
                                    print(self.des_dir)
                                    wget.download(i, out=self.des_dir)
                                    self.valid_images.append(i)
                            self.content_image_arrived.emit(self.valid_images, self.des_dir)

                        elif page == 'Summary':
                            self.content_text_arrived.emit(wiki.summary)
                        elif page == 'Images Links':
                            self.content_link_arrived.emit(wiki.images)
                        elif page == 'References Links':
                            self.content_link_arrived.emit(wiki.references)


                    except:
                        self.error_occurred.emit()

            self.progress_thread = ProgressThread()
            self.progress_thread.content_link_arrived.connect(self.set_content_link)
            self.progress_thread.content_text_arrived.connect(self.set_content_text)
            self.progress_thread.content_image_arrived.connect(self.set_content_image)
            self.progress_thread.error_occurred.connect(self.handle_error_occurred)
            self.progress_thread.start()
        else:
            self.content_text_browser.clear()
            self.content_text_browser.setEnabled(False)