Skip to content

Instantly share code, notes, and snippets.

@Macuyiko
Last active January 10, 2017 08:18
Show Gist options
  • Save Macuyiko/a8a90554428064db98d73c65b30abb80 to your computer and use it in GitHub Desktop.
Save Macuyiko/a8a90554428064db98d73c65b30abb80 to your computer and use it in GitHub Desktop.
import win32com.client
from flask import Flask, request, jsonify
def get_corrections(text, language=1033):
# See https://technet.microsoft.com/en-us/library/cc179219.aspx for a list of language ids
word = win32com.client.Dispatch('Word.Application')
word.Visible = True
wordDoc = word.Documents.Add()
wordDoc.Range().LanguageID = language
wordDoc.Range().Text = text
corrections = {'spelling': [],
'grammar': [],
'spellingcount': 0,
'grammarcount': 0,
'text': text}
def rng_to_dict(rng):
d = {'text': rng.Text, 'start': rng.Start, 'end': rng.End, 'suggestions': []}
for i in range(1, rng.GetSpellingSuggestions().Count+1):
d['suggestions'].append(rng.GetSpellingSuggestions().Item(i).Name)
return d
for rng in wordDoc.Range().SpellingErrors:
corrections['spelling'].append(rng_to_dict(rng))
corrections['spellingcount'] += 1
for rng in wordDoc.Range().GrammaticalErrors:
corrections['grammar'].append(rng_to_dict(rng))
corrections['grammarcount'] += 1
wordDoc.Close(SaveChanges=0)
word.Quit()
return corrections
app = Flask(__name__)
@app.route("/spellcheck/", methods=['GET', 'POST'])
def spellcheck():
language = request.args.get('language') or request.form.get('language') or 1033
text = request.args.get('text') or request.form.get('text') or ''
print(language, text)
return jsonify(get_corrections(text, language))
if __name__ == "__main__":
app.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment