#command-line #python
#командная строка #python
Вопрос:
Я создаю утилиту 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:UsersckyiuOneDriveDesktopPython Information Engine 2.1.py", line 210, in <module>
search(q)
File "C:UsersckyiuOneDriveDesktopPython Information Engine 2.1.py", line 62, in search
res = client.query(text)
File "C:UsersckyiuAppDataLocalProgramsPythonPython37-32libsite-packageswolframalpha__init__.py", line 56, in query
return Result(resp)
File "C:UsersckyiuAppDataLocalProgramsPythonPython37-32libsite-packageswolframalpha__init__.py", line 178, in __init__
super(Result, self).__init__(doc)
File "C:UsersckyiuAppDataLocalProgramsPythonPython37-32libsite-packageswolframalpha__init__.py", line 62, in __init__
self._handle_error()
File "C:UsersckyiuAppDataLocalProgramsPythonPython37-32libsite-packageswolframalpha__init__.py", line 69, in _handle_error
raise Exception(template.format(**self))
Exception: Error 0: Unknown error
Комментарии:
1. После этого утверждения я получил ошибку выше: print («Это все на сегодня!») @Scott, я работаю над mvce, спасибо
Ответ №1:
Что ж, теперь у меня все заработало, по какой-то причине я поставил: if (q != 'News'):
Я хотел if (q != 'Latest News'):
.
Затем python выдал мне ошибку для этого. По крайней мере, сейчас я заставил это работать.