Advertisement
Guest User

Untitled

a guest
Nov 23rd, 2017
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.03 KB | None | 0 0
  1. """Search for things related to a location and returns a list related to what was searched for"""
  2.  
  3. #import library to access webpage
  4. import json
  5. import requests
  6. import urllib.request
  7. from key import key1, app_key, app_id, language #import from key.py
  8.  
  9. userinput = input(""">""") #enter user input
  10. userinput.lower() #make userinput lower case
  11. listSynonyms = [] #empty synonyms list
  12.  
  13. #function for putting all synonyms in list of synonyms
  14. #documentation for API found in https://developer.oxforddictionaries.com/documentation under the synonyms section
  15. def synonyms():
  16.    
  17.     wordSynonyms = ['near','close','in'] #list of words that will be searched for synonyms
  18.     urlList = [] #empty url list
  19.     n=0 #set the value of n as 0
  20.    
  21.     #appends the list of url for synonyms for each specfic word in wordSynonyms
  22.     for n in range(len(wordSynonyms)): #iterates as many times as the length of wordSynonyms
  23.         url = 'https://od-api.oxforddictionaries.com:443/api/v1/entries/' + language + '/' + wordSynonyms[n].lower() + '/synonyms' #
  24.         n+=1 #increment n by 1
  25.         urlList.append(url) #append url to urlList
  26.    
  27.     #get webpages listed in urlList
  28.     near = requests.get(urlList[0], headers = {'app_id': app_id, 'app_key': app_key})
  29.     close = requests.get(urlList[1], headers = {'app_id': app_id, 'app_key': app_key})
  30.     pIn = requests.get(urlList[2], headers = {'app_id': app_id, 'app_key': app_key})
  31.  
  32.     #decode json data
  33.     rawWebDict1 = near.json()
  34.     rawWebDict2 = close.json()
  35.     rawWebDict3 = pIn.json()
  36.  
  37.     i=0 #set value of i to 0
  38.  
  39.     #append the list according to their synonyms (near, close, in).
  40.     #This list contains synonyms of the word to allow other userinput related to the word
  41.     for i in range(len(rawWebDict1["results"][0]["lexicalEntries"][0]["entries"][0]["senses"][0]["synonyms"])): #for every list of synonyms related to near
  42.         synonyms1 = rawWebDict1["results"][0]["lexicalEntries"][0]["entries"][0]["senses"][0]["synonyms"][i]["text"] #goes to every list
  43.         i+=1 #increment by 1
  44.         listSynonyms.append(synonyms1) #append each synonyms to list of synonyms
  45.  
  46.     #same process happen but for word "close"
  47.     for i in range(len(rawWebDict2["results"][0]["lexicalEntries"][0]["entries"][0]["senses"][0]["synonyms"])):
  48.         synonyms2 = rawWebDict2["results"][0]["lexicalEntries"][0]["entries"][0]["senses"][0]["synonyms"][i]["text"]
  49.         i+=1
  50.         listSynonyms.append(synonyms2)
  51.     #same process happen but for word "in"
  52.     for i in range(len(rawWebDict3["results"][0]["lexicalEntries"][0]["entries"][0]["senses"][0]["synonyms"])):
  53.         synonyms3 = rawWebDict3["results"][0]["lexicalEntries"][0]["entries"][0]["senses"][0]["synonyms"][i]["text"]
  54.         i+=1
  55.         listSynonyms.append(synonyms3)
  56.  
  57. #function for removing irrelevant sentence
  58. def removesentence(userinput):
  59.     listWords = userinput.split() #split the string
  60.     if len(listWords) == 1: #if length of listWords is 1 -- this means the user input @places without any strings following it
  61.         print("I think you got it wrong! To search for places near the area just use @places: '@places bars near coventry'") #tells the user the correct format
  62.     elif listWords[0] == "@places": #checks if the first element on the list is "@places"
  63.         listWords.pop(0) #removes the index containing @places
  64.         strings = str(listWords).strip('[]') #removes square brackets
  65.         place = ",".join(listWords).replace(","," ") #joins together by a comma and separates by space
  66.         placesearch(place)
  67.     else: #if the above is not true then run this part of the code
  68.         listIndex = [i for i in range(len(listWords)) if listWords[i] == '@places'] #takes the index containing @places
  69.         cStr = str(listIndex).strip('[]') #strip the brackets
  70.         cInt = int(cStr) #convert string to integer
  71.         del listWords[0:cInt+1] #removes the first index until the index containing string
  72.         place = ",".join(listWords).replace(","," ") #replace the comma and put a space to join the words
  73.         placesearch(place) #goes to the function placesearch(search)
  74.  
  75. def placesearch(search):
  76.     synonyms() #goes to the synonyms function
  77.     validList = ["near","close by","close","in"] #list of validList
  78.     placeSearch = search.replace(" ","+") #replace the separator with + so that it can be use for url
  79.     #retrive data from a website
  80.     with urllib.request.urlopen("https://maps.googleapis.com/maps/api/place/textsearch/json?query=" + placeSearch + key1 ) as response:
  81.        rawWebData = response.read().decode('utf8') #decode web data
  82.  
  83.     #decode the data retrived from json format into lists/dictionaries
  84.     decodedWebData = json.loads(rawWebData)
  85.     List = []
  86.     if decodedWebData["status"] == "OK": #this checks if there are actual search results
  87.        
  88.         if any(substring in search for substring in validList) or  any(substring in search for substring in listSynonyms): #checks if the input is in validList or listSynonyms
  89.             i=0  #set i equivalent to 0          
  90.             for i in range(len(decodedWebData["results"])): #iterates by the number of results in the webData
  91.                 #prints the relevant data related to what is searched for but checks if key exist          
  92.                 if "name" not in decodedWebData["results"][i]:
  93.                     continue
  94.                 else:      
  95.                     near = decodedWebData["results"][i]["name"]
  96.                     List.append("\n"+near)
  97.  
  98.                 if "formatted_address" not in decodedWebData["results"][i]:
  99.                     continue
  100.                 else:
  101.                     address = decodedWebData["results"][i]["formatted_address"]
  102.                     List.append("Address: " + address)
  103.                    
  104.                 if "rating" not in decodedWebData["results"][i]:
  105.                     continue
  106.                 else:
  107.                     rating = decodedWebData["results"][i]["rating"]
  108.                     List.append("Rating: "+ str(rating))
  109.                
  110.                 if "photos" not in decodedWebData["results"][i]:
  111.                     continue
  112.                 else:
  113.                     link = decodedWebData["results"][i]["photos"][0]["html_attributions"]
  114.                     List.append("Link: " + str(link))
  115.                
  116.                 final = ""
  117.                 for i in range(0,len(List)):
  118.                     final = final + "\n" + List[i]
  119.                
  120.                 return(final)
  121.                 i+=1 #increment by 1
  122.  
  123.     else: #if there is no search result then this means that the format is either invalid or the place is spelled incorrectly
  124.         print("""I think you put an invalid place or your format is wrong. Remember you have to follow this format: @places bars near coventry.""")
  125.  
  126. if "@places" in userinput:
  127.     removesentence(userinput)
  128. elif "@place" in userinput:
  129.     print("You got it wrong please use '@places' instead")
  130. else:
  131.     print("I think you got it wrong! To search for places near the area just use @places: '@places bars near coventry'")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement