import requests def correct_sentence(text): """ Corrects the given text using the Ginger grammar correction API. Parameters: text (str): The text to be corrected. Returns: str: The corrected text with grammar suggestions applied. """ # Ginger grammar correction API URL ginger_api_url = 'https://services.gingersoftware.com/Ginger/correct/jsonSecured/GingerTheTextFull' # Ginger API parameters params = { 'lang': 'US', # Language set to English (US) 'clientVersion': '2.0', # Version of the Ginger API 'apiKey': '6ae0c3a0-afdc-4532-830c-53f0f02e2f0c', # Public API key 'text': text # Text that needs grammar correction } try: # Send a GET request to the Ginger API response = requests.get(ginger_api_url, params=params) # Check if the request was successful if response.status_code == 200: # Parse the JSON response data = response.json() # If no corrections are found, return the original text if not data['LightGingerTheTextResult']: return text # Correct the text based on the suggestions corrected_text = apply_corrections(text, data['LightGingerTheTextResult']) return corrected_text else: # If the request failed, return the original text return text except requests.exceptions.RequestException as e: # Handle any exceptions (like network errors) print(f"An error occurred: {e}") return text def apply_corrections(text, corrections): """ Applies the corrections suggested by the Ginger API. Parameters: text (str): The original text. corrections (list): A list of correction suggestions from Ginger. Returns: str: The corrected text with suggestions applied. """ corrected_text = list(text) # Offset helps adjust the position as we modify the string offset = 0 for correction in corrections: start = correction['From'] + offset end = correction['To'] + 1 + offset # Replace the incorrect part with the suggestion suggestion = correction['Suggestions'][0]['Text'] # Replace the text within the correct range corrected_text[start:end] = suggestion # Adjust offset based on length difference between suggestion and original offset += len(suggestion) - (end - start) return ''.join(corrected_text) def main(): """ Main function for grammar correction. Prompts the user to enter a sentence and corrects the grammar. """ # Input sentence from the user sentence = input("Enter a sentence to correct: ") # Correct the sentence using Ginger corrected_sentence = correct_sentence(sentence) # Display the corrected sentence print("Corrected Sentence: ", corrected_sentence) if __name__ == "__main__": main()