遍历所有可用新闻文章后的追溯

时间:2019-03-22 23:21:05

标签: command-line python

我正在制作一个python CLI实用程序,它将回答“ 15 + 15”或“字母表中有多少个字母”之类的问题。

然后,我决定增加使用 newspaper 模块搜索最新新闻的功能。

除打印 for 循环完成后,所有其他功能均有效,在打印字符串文字后,它给我一个错误,我不知道这是什么意思。

有人可以帮我破译该错误吗?如果可以,可以帮助我解决该错误吗?谢谢。

ggplot_global.new$element_tree$strip.background <- ggplot2:::el_def("element_rect", "rect")
ggplot_global.new$element_tree$strip.background.x <- ggplot2:::el_def("element_rect", "strip.background")
ggplot_global.new$element_tree$strip.background.y <- ggplot2:::el_def("element_rect", "strip.background")

untrace(ggplot2:::merge_element.element)
untrace(ggplot2:::validate_element)

这是错误:

import requests
import wolframalpha
import wikipedia
import time
import sys
from threading import Thread
from newspaper import Article
import bs4
from bs4 import BeautifulSoup as soup
from urllib.request import urlopen

version = 2.1
build = '19w12a6'

ready = 0
loadingAnimationStop = 0

appId = 'YGK5P2-98TU6K2P34'
client = wolframalpha.Client(appId)

exitNow = 0

def loadingAnimation():
    while exitNow == 0:
        print("Loading: |", end='\r')
        time.sleep(0.2)
        while ready == 1:
            time.sleep(0)
        print("Loading: /", end='\r')
        time.sleep(0.2)
        while ready == 1:
            time.sleep(0)
        print("Loading: -", end='\r')
        time.sleep(0.2)
        while ready == 1:
            time.sleep(0)
        sys.stdout.write("Loading: \ \r")
        time.sleep(0.2)
        while ready == 1:
            time.sleep(0)

hui = Thread(target = loadingAnimation, args=())
hui.start()

def search_wiki(keyword=''):
    searchResults = wikipedia.search(keyword)
    if not searchResults:
        print("No result from Wikipedia")
        return
    try:
        page = wikipedia.page(searchResults[0])
    except wikipedia.DisambiguationError:
        page = wikipedia.page(err.options[0])
    wikiTitle = str(page.title.encode('utf-8'))
    wikiSummary = str(page.summary.encode('utf-8'))
    print('              ', end='\r')
    print(wikiTitle)
    print(wikiSummary)


def search(text=''):
    res = client.query(text)
    if res['@success'] == 'false':
        ready = 1
        time.sleep(1)
        print('Query cannot be resolved')
    else:
        result = ''
        pod0 = res['pod'][0]
        pod1 = res['pod'][1]

    if (('definition' in pod1['@title'].lower()) or ('result' in  pod1['@title'].lower()) or (pod1.get('@primary','false') == 'True')):
        result = resolveListOrDict(pod1['subpod'])
        ready = 1
        time.sleep(0.75)
        print('              ', end='\r')
        print(result)
        question = resolveListOrDict(pod0['subpod'])
        question = removeBrackets(question)
        #primaryImage(question)
    else:
        question = resolveListOrDict(pod0['subpod'])
        question = removeBrackets(question)
        search_wiki(question)


def removeBrackets(variable):
    return variable.split('(')[0]

def resolveListOrDict(variable):
    if isinstance(variable, list):
        return variable[0]['plaintext']
    else:
        return variable['plaintext']

#def primaryImage(title=''):
#    url = 'http://en.wikipedia.org/w/api.php'
#    data = {'action':'query', 'prop':'pageimages','format':'json','piprop':'original','titles':title}
#    try:
#        res = requests.get(url, params=data)
#        key = res.json()['query']['pages'].keys()[0]
#        imageUrl = res.json()['query']['pages'][key]['original']['source']
#        print(imageUrl)
#    except Exception:
#        print('Exception while finding image:= '+str(err))

page = requests.get('https://www.wolframalpha.com/')

s = page.status_code

if (s != 200):
    ready = 1
    time.sleep(1)
    print('It looks like https://www.wolframalpha.com/ is not online.')
    print('Please check your connection to the internet and https://www.wolframalpha.com/')
    print('Stopping Python Information Engine')
    while True:
        time.sleep(1)

page = requests.get('https://www.wikipedia.org/')

s = page.status_code

if (s != 200):
    ready = 1
    time.sleep(1)
    print('It looks like https://www.wikipedia.org/ is not online.')
    print('Please check your connection to the internet and https://www.wikipedia.org/')
    print('Stopping Python Information Engine')
    while True:
        time.sleep(1)

ready = 1

while exitNow == 0:
    print('================================================================================================')
    print('Python Information Engine CLI Version', end=' ')
    print(version)
    print('Create by Unsigned_Py')
    print('================================================================================================')
    ready = 1
    time.sleep(1)
    print('                                                                                                ', end='\r')
    print('       ', end='\r')
    q = input('Search: ')
    print('================================================================================================')
    if (q == 'Credits()'):
        print('Credits')
        print('================================================================================================')
        print('PIE is made by Unsigned_Py')
        print('Unsigned_Py on the Python fourms: https://python-forum.io/User-Unsigned-Py')
        print('Contact Unsigned_Py: Ckyiu@outlook.com')
    if (q == 'Latest News'):
        print('DISCLAIMER: The Python Information Engine News port is still in DEVELOPMENT!')
        print('Getting latest news links from Google News...')
        ready = 0

        news_url = "https://news.google.com/news/rss"
        Client = urlopen(news_url)
        xml_page = Client.read()
        Client.close()

        soup_page = soup(xml_page,"xml")
        news_list = soup_page.findAll("item")

        ready = 1

        print('================================================================================================')

        article_number = 1

        for news in news_list:
            print(article_number, end=': ')
            print(news.title.text)
            print(news.pubDate.text)
            if (input('Read (Y or N)? ') == 'y'):
                ready = 0
                url = news.link.text
                article = Article(url)

                article.download()
                article.parse()

                article.nlp()

                ready = 1

                print('================================================================================================')
                print(article.summary)
            print('================================================================================================')
            article_number = article_number + 1


        print("That's all for today!")

    if (q == 'Version()'):
        print('Python Information Engine CLI Version', end=' ')
        print(version)
        print('Running Build', end=' ')
        print(build)
        print('Upon finding a bug, please report to Unsigned_Py and I will try to fix it!')
        print('Looking for Python Information Engine CLI Version 1.0 - 1.9?')
        print("It's called Wolfram|Alpha and Wikipedia Engine Search!")

    if (q != 'Exit()'):
        if (q != 'Credits()'):
            if (q != 'News'):
                if (q != 'Version()'):
                    ready = 0
                    search(q)
    else:
        exitNow = 1

print('Thank you for using Python Information Engine')
print('================================================================================================')
time.sleep(2)
ready = 0




1 个答案:

答案 0 :(得分:0)

好吧,由于某种原因,我现在开始使用它了:Traceback (most recent call last): File "C:\Users\ckyiu\OneDrive\Desktop\Python Information Engine 2.1.py", line 210, in <module> search(q) File "C:\Users\ckyiu\OneDrive\Desktop\Python Information Engine 2.1.py", line 62, in search res = client.query(text) File "C:\Users\ckyiu\AppData\Local\Programs\Python\Python37-32\lib\site-packages\wolframalpha\__init__.py", line 56, in query return Result(resp) File "C:\Users\ckyiu\AppData\Local\Programs\Python\Python37-32\lib\site-packages\wolframalpha\__init__.py", line 178, in __init__ super(Result, self).__init__(doc) File "C:\Users\ckyiu\AppData\Local\Programs\Python\Python37-32\lib\site-packages\wolframalpha\__init__.py", line 62, in __init__ self._handle_error() File "C:\Users\ckyiu\AppData\Local\Programs\Python\Python37-32\lib\site-packages\wolframalpha\__init__.py", line 69, in _handle_error raise Exception(template.format(**self)) Exception: Error 0: Unknown error 我想要if (q != 'News'):

然后python为此抛出了一个错误。我至少现在能正常工作。