首页 > 解决方案 > 遍历所有可用新闻文章后的回溯

问题描述

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

然后我决定添加使用报纸模块搜索最新消息的功能。

所有这些都有效,除非for循环完成,在打印字符串文字后,它给了我一个错误,我不知道这到底是什么意思。

有人可以为我破译错误,如果可能的话,帮我修复错误?谢谢。

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 = 'CENSORED STUFF BECAUSE I DON\'T WANT ANYONE TO TOUCH MY KEY'
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




这是错误:

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

标签: command-linepython

解决方案


好吧,我现在开始工作了,出于某种原因,我说:if (q != 'News'):我想要if (q != 'Latest News'):.

然后python为此向我抛出了一个错误。至少现在我让它工作了。


推荐阅读