Advertisement
Guest User

Untitled

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