-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathginger.py
90 lines (76 loc) · 2.42 KB
/
ginger.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Simple grammar checker
This grammar checker will fix grammar mistakes using Ginger.
"""
import sys
import urllib
import urlparse
from urllib2 import HTTPError
from urllib2 import URLError
import json
from nltk.tokenize import sent_tokenize
out=""
def get_ginger_url(text):
"""Get URL for checking grammar using Ginger.
@param text English text
@return URL
"""
API_KEY = "6ae0c3a0-afdc-4532-a810-82ded0054236"
scheme = "http"
netloc = "services.gingersoftware.com"
path = "/Ginger/correct/json/GingerTheText"
params = ""
query = urllib.urlencode([
("lang", "US"),
("clientVersion", "2.0"),
("apiKey", API_KEY),
("text", text)])
fragment = ""
return(urlparse.urlunparse((scheme, netloc, path, params, query, fragment)))
def get_ginger_result(text):
"""Get a result of checking grammar.
@param text English text
@return result of grammar check by Ginger
"""
url = get_ginger_url(text)
try:
response = urllib.urlopen(url)
except HTTPError as e:
print("HTTP Error:", e.code)
quit()
except URLError as e:
print("URL Error:", e.reason)
quit()
try:
result = json.loads(response.read().decode('utf-8'))
except ValueError:
print("Value Error: Invalid server response.")
quit()
return(result)
def ginger(text):
results = get_ginger_result(text)
if(not results["LightGingerTheTextResult"]):
if len(text)!=0:
data=str(file("corrected.txt","r").read())
data+=text+"\n"
file("corrected.txt","w").write(data)
return
else:
for result in results["LightGingerTheTextResult"]:
if(result["Suggestions"]):
from_index = result["From"]
to_index = result["To"] + 1
suggest = result["Suggestions"][0]["Text"]
if text[:from_index]==" ":
fixed_text=suggest+text[to_index:]
elif text[to_index:]==" ":
fixed_text=text[:from_index]+suggest
else:
fixed_text=text[:from_index]+suggest+text[to_index:]
ginger(fixed_text)
def main(filename):
file("corrected.txt","w")
sent=sent_tokenize(file(filename,"r").read())
for i in range(len(sent)):
ginger(sent[i])