import wikipedia
import os
while True:
input = raw_input("Ques: ")
#To get output in a particular language ,
#This prints the results on spanish
#wikipedia.set_lang("es")
wiki = wikipedia.summary(input, sentences = 2).encode('utf-8').strip()
os.system("say " + wiki)
print wiki
on the output console, it asks for
Ques: when I type Cristiano
It says "Cristiano is a Portuguese footballer"
But when I type anything other than Cristiano (Say Chelsea FC), it says
sh: -c: line 0: unexpected EOF while looking for matching `''
sh: -c: line 1: syntax error: unexpected end of file
OR
sh: -c: line 0: syntax error near unexpected token `('
The returning value of wikipedia.summary() may contain characters that the shell interprets with special meaning. You can escape such characters with shlex.quote():
import wikipedia
import os
import shlex
while True:
input = raw_input("Ques: ")
#To get output in a particular language ,
#This prints the results on spanish
#wikipedia.set_lang("es")
wiki = wikipedia.summary(input, sentences = 2).encode('utf-8').strip()
os.system("say " + shlex.quote(wiki))
print wiki
I haven't work with wikipedia third-party before. But when I try your code and I found that I just need to delete .encode('utf-8'). And it's work for me.
wiki = wikipedia.summary(i, sentences=2).strip()
import wikipedia
import os
while True:
i = input("Ques: ")
#To get output in a particular language ,
#This prints the results on spanish
#wikipedia.set_lang("es")
wiki = wikipedia.summary(i, sentences=2).strip()
os.system("say "+ wiki)
print(wiki)
Result: Chelsea Football Club is a professional football club in London, England, that competes in the Premier League. Founded in 1905, the club's home ground since then has been Stamford Bridge.Chelsea won the First Division title in 1955, ....
Or you can you use another third-party like pyttsx3: pip install pyttsx3.
And the code will be like this:
import wikipedia
import pyttsx3
engine = pyttsx3.init()
while True:
i = input("Ques: ")
wiki = wikipedia.summary(i, sentences=2).strip()
# os.system("say "+ wiki)
print(wiki)
engine.say(wiki)
engine.runAndWait()`
I hope it can help.
Related
I want to use deepl translate api for my university project, but I can't parse it. I want to use it wit PHP or with Python, because the argument I'll pass to a python script so it's indifferent to me which will be the end. I tried in php like this:
$original = $_GET['searchterm'];
$deeplTranslateURL='https://api-free.deepl.com/v2/translate?auth_key=MYKEY&text='.urlencode($original).'&target_lang=EN';
if (get_headers($deeplTranslateURL)[0]=='HTTP/1.1 200 OK') {
$translated = str_replace(' ', '', json_decode(file_get_contents($deeplTranslateURL))["translations"][0]["text"]);
}else{
echo("translate error");
}
$output = passthru("python search.py $original $translated");
and I tried also in search.py based this answer:
#!/usr/bin/env python
import sys
import requests
r = requests.post(url='https://api.deepl.com/v2/translate',
data = {
'target_lang' : 'EN',
'auth_key' : 'MYKEY',
'text': str(sys.argv)[1]
})
print 'Argument:', sys.argv[1]
print 'Argument List:', str(sys.argv)
print 'translated to: ', str(r.json()["translations"][0]["text"])
But neither got me any answer, how can I do correctly? Also I know I can do it somehow in cURL but I didn't used that lib ever.
DeepL now has a python library that makes translation with python much easier, and eliminates the need to use requests and parse a response.
Get started as such:
import deepl
translator = deepl.Translator(auth_key)
result = translator.translate_text(text_you_want_to_translate, target_lang="EN-US")
print(result)
Looking at your question, it looks like search.py might have a couple problems, namely that sys splits up every individual word into a single item in a list, so you're only passing a single word to DeepL. This is a problem because DeepL is a contextual translator: it builds a translation based on the words in a sentence - it doesn't simply act as a dictionary for individual words. If you want to translate single words, DeepL API probably isn't what you want to go with.
However, if you are actually trying to pass a sentence to DeepL, I have built out this new search.py that should work for you:
import sys
import deepl
auth_key="your_auth_key"
translator = deepl.Translator(auth_key)
"""
" ".join(sys.argv[1:]) converts all list items after item [0]
into a string separated by spaces
"""
result = translator.translate_text(" ".join(sys.argv[1:]), target_lang = "EN-US")
print('Argument:', sys.argv[1])
print('Argument List:', str(sys.argv))
print("String to translate: ", " ".join(sys.argv[1:]))
print("Translated String:", result)
I ran the program by entering this:
search.py Der Künstler wurde mit einem Preis ausgezeichnet.
and received this output:
Argument: Der
Argument List: ['search.py', 'Der', 'Künstler', 'wurde', 'mit', 'einem',
'Preis', 'ausgezeichnet.']
String to translate: Der Künstler wurde mit einem Preis ausgezeichnet.
Translated String: The artist was awarded a prize.
I hope this helps, and that it's not too far past the end of your University Project!
I'm running a script to get pages related to a word using python (pip3 install wikipedia). I enter a word to search, let's say the word is "cat". I send that to the code below, but the wikipedia code changes it to "hat" and returns pages related to "hat". It does this with any word I search for (ie: "bear" becomes "beard". "dog" becomes "do", etc...)
wikipedia_page_name = "cat"
print("Original: ", wikipedia_page_name)
myString = wikipedia.page(wikipedia_page_name)
print("Returned: ", myString)
Here is what I get back:
Original: cat
Returned: <WikipediaPage 'Hat'>
My steps to use this were to install wikipedia "pip3 install wikipedia" and then import it "import wikipedia". That's it! I've tried uninstalling and then reinstalling, but I get the same results.
Any help is appreciated!
If you want to work with the page <WikipediaPage 'Cat'>, please try to set auto_suggest to False as suggest can be pretty bad at finding the right page:
import wikipedia
wikipedia_page_name = "cat"
print("Original: ", wikipedia_page_name)
myString = wikipedia.page(wikipedia_page_name, pageid=None, auto_suggest=False)
print("Returned: ", myString)
Output:
Original: cat
Returned: <WikipediaPage 'Cat'>
If you want to find titles, use search instead:
import wikipedia
wikipedia_page_name = "cat"
searches = wikipedia.search(wikipedia_page_name)
print(searches)
Output:
['Cat', 'Cat (disambiguation)', 'Keyboard Cat', 'Calico cat', 'Pussy Cat Pussy Cat', 'Felidae', "Schrödinger's cat", 'Tabby cat', 'Bengal cat', 'Sphynx cat']
You can use both together to make sure you get the right page from a String, as such:
import wikipedia
wikipedia_page_name = "cat"
searches = wikipedia.search(wikipedia_page_name)
if searches:
my_page = wikipedia.page(searches[0], pageid=None, auto_suggest=False)
print(my_page)
else:
print("No page found for the String", wikipedia_page_name)
Output:
<WikipediaPage 'Cat'>
I am very new to python and writing a script that will extract a few URLs from two configuration files. The following is the body of the script as of now:
import os
import sys
import logging
logger = logging.getLogger('check_store')
logger.setLevel(logging.DEBUG)
env= raw_input("Enter environmentname (ex. dev/qa/prod): ")
cust= raw_input("Enter customer name: ")
engage_properties= '/opt/engage/engageconf.properties'
symmetric_properties= '/opt/engage/symmetric.properties'
with open ("%s" % (engage_properties)) as inF:
for line in inF:
if ("%s-%s.%sfqdn.com" % (env,cust,env)) in line:
print line
The output as as follows:
Enter environmentname (ex. dev/qa/prod): qa
Enter customer name: cust
connect.rest.address=http://connect.qa-cust.qafqdn.com
connect.rest.ssl.address=https://connect.qa-cust.qafqdn.com
connect.rest.giftregistry.service=http://connect.qa-cust.qafqdn.com:8280/services
receipt.server.host=engage.central.qa-cust.qafqdn.com
What I am trying to accomplish is having the script specifically look for the following as also shown above:
connect.rest.address=
connect.rest.ssl.address=
connect.rest.giftregistry.service=
and report back to the user if one of them is incorrect..
So, if i enter in when prompted: 'qa' for then env name and 'cust' for the customer name, if either of the URLs have anything other than something formatted like so:
connect.qa-cust.qafqdn.com
then it will tell the user which of the three URL variables are not formatted correctly.
So, to clarify.. if 'connect.rest.ssl.address=' did not equal the input that I provided (equaling qa-cust.qafqdn.com) but the rest of them did, then I would see an error like:
connect.rest.address - OK
connect.rest.ssl.address - ERROR: does not match value provided
connect.rest.giftregistry.service - OK
This script is basically a environment sanity checker.
I tried to make this as clear as possible and I appreciate the assistance.
I'm not sure I understood the question properly, but if you are expecting any line in the file to have the correct properties, then if the line has part of but not all of the correct formatting it is wrong.
with open ("%s" % (engage_properties)) as inF:
for line in inF:
if ("%s-%s.%srhythmforstores.com" % (env,cust,env)) in line:
print line
elif "rhythmforstores.com" in line:
print error_message
I'm messing around with Google Speech Recognition in Python. The idea is that it will listen to what I say, and then give me back a response/action based on that. Here is the code:
import time
from gtts import gTTS
import os
import speech_recognition as sr
import pyaudio
r = sr.Recognizer()
def speak(audioString):
print(audioString)
tts = gTTS(text=audioString, lang='en')
#tts.save("audio.mp3")
#os.system("audio.mp3")
# obtain audio from the microphone
def recordAudio():
r = sr.Recognizer()
with sr.Microphone() as source:
print("Listening")
audio = r.listen(source)
# recognize speech using Google Speech Recognition
try:
# using the default API key
# to use another API key, use `r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")`
data = r.recognize_google(audio)
except sr.UnknownValueError:
print("Google Speech Recognition could not understand audio")
except sr.RequestError as e:
print("Could not request results from Google Speech Recognition service; {0}".format(e))
def assistant(data):
if "how are you" in data:
print("I am fine")
if "what time is it" in data:
print(ctime())
if "where is" in data:
data = data.split(" ")
location = data[2]
speak("Hold on, I will show you where " + location + " is.")
os.system("chromium-browser https://www.google.nl/maps/place/" + location + "/&")
# initialization
time.sleep(3)
print("Hi, what can I do for you?")
print(data)
while 1:
data = recordAudio()
print(data)
assistant(data)
Now, the error:
Listening
Hi, what can I do for you?
how are you
None
Traceback (most recent call last):
File "C:/Python34/speechrecogtest.py", line 54, in <module>
assistant(data)
File "C:/Python34/speechrecogtest.py", line 35, in assistant
if "how are you" in data:
TypeError: argument of type 'NoneType' is not iterable
It's hearing what I'm saying, I have it printing that out. When I say "How are you" it should print out "I am fine" but is not...
I don't understand how this is a NoneType error. I have a feeling that it is not reading the data string in the arguments in the "def assistant(data):" area, because I've got a function messed up somewhere... This is definitely something stupidly obvious. What is wrong with those functions?
EDIT:
If I do something like:
print("Hi, what can I do for you?")
while 1:`
data = recordAudio()
if "how are you" in data:
print("I am fine")
That works beautifully!
The problem is mainly that I am trying to call the assistant(data) function, so that it will say what I want it to say based on pre-defined responses.
I keep getting errors when I try to pass it to the assistant(data) function. That's really what I need help with, it looks like. I keep getting all sorts of errors when I try to get it to print from there
I am currently building a personal assistant bot as a challenge while I am on school break. It has previously had no issues, but I started getting TypeErrors, despite the fact that I am able to check that "speech" is returning as a string. I know this because the TypeError will randomly pop up after a few times of running through the while True loop (so "speech" must only not be returning as a string then...)
I've found other pages on TypeErrors and things returning None and NonTypes like one and two, but neither seem to help my predicament. I've also browsed through countless other pages trying to find things that help, but to no avail.
The error always brings up line 19:
import speech_recognition as sr
from chatterbot import ChatBot
import Messanger_Alert as MA
import Weather
import Email_Alert
import Chat
import Run
def start():
#bot = Chat.start()
MA_client = MA.login()
print "Hello Luke!"
print "I am ready for your command! :D"
while True:
speech = return_audio()
try:
if any(word in speech for word in ("Jason", "jason")): #This is line 19
if any(word in speech for word in ("Message", "message", "Messenger", "messenger", "Facebook", "facebook")):
if any(word in speech for word in ("Send", "send")):
MA.send_message(MA_client)
print "Ready for next command!"
elif any(word in speech for word in ("Search Friend", "search friend", "Seach friend", "search Friend", "friend", "Friend", "friends", "Friends")):
MA.friend_search(MA_client)
print "Ready for next command!"
elif any(word in speech for word in ("Check", "check")):
MA.check_message(MA_client)
print "Ready for next command!"
elif any(word in speech for word in ("Email", "email")):
if any(word in speech for word in ("Personal", "personal", "Home", "home")):
Email_Alert.login1()
print "Ready for next command!"
elif any(word in speech for word in ("School", "school", "Dorm", "dorm", "UCSD", "ucsd")):
Email_Alert.login2()
print "Ready for next command!"
elif any(word in speech for word in ("Weather", "weather", "Forecast", "forecast")):
Weather.decide()
"""else:
Chat.talk(bot)
else:
Chat.talk(bot)
"""
except sr.UnknownValueError:
print "Error! Could not process that audio."
except sr.RequestError as e:
print "Error! No internet connection to Google Sound Recognizer."
def return_audio():
r = sr.Recognizer()
with sr.Microphone() as source:
audio = r.listen(source)
try:
speech = r.recognize_google(audio)
try:
speech = str(speech)
print speech
return speech
except TypeError:
print "Error! Could not convert speech to string!"
except sr.UnknownValueError:
print "Error! Could not process that audio."
except sr.RequestError as e:
print "Error! No internet connection to Google Sound Recognizer."
This is the exact error I get:
Traceback (most recent call last):
File "C:/Users/lukec/PycharmProjects/Sysgen_AI/Run_File.py", line 25, in <module>
startup()
File "C:/Users/lukec/PycharmProjects/Sysgen_AI/Run_File.py", line 14, in startup
voice()
File "C:/Users/lukec/PycharmProjects/Sysgen_AI/Run_File.py", line 20, in voice
Listen.start()
File "C:\Users\lukec\PycharmProjects\Sysgen_AI\Listen.py", line 19, in start
if any(word in speech for word in ("Jason", "jason")):
File "C:\Users\lukec\PycharmProjects\Sysgen_AI\Listen.py", line 19, in <genexpr>
if any(word in speech for word in ("Jason", "jason")):
TypeError: argument of type 'NoneType' is not iterable
I noticed that the TypeError arises more often when strange noises are heard that cannot be distinguished into words, but I don't get why. I first noticed this error when I had a Chatbot library conversation bot take over when a command wasn't being issued, and thought when I cut it out of my code the errors would stop, but that didn't fix it. Any help on fixing it and explaining why to me would be greatly appreciated.
If you'd need my extra files (Messanger_Alert, Weather, etc.), I'm willing to supply that code if it could possibly help.
Thank you for your help!
With if any(word in speech for word in ("Jason", "jason")):, Python is attempting to check whether either word is in speech. You get speech from return_audio(). When return_audio() encounters any of the specified exceptions, it does not execute any explicit return statement, therefore implicitly returning None, which can't be iterated over in search of anything.
To fix this, simply check whether that function produced a real result before you try to look through that result.
while True:
speech = return_audio()
if not speech:
continue