Information in this document is subject to change without notice. The example companies, organizations, products, people, and events depicted herein are fictitious. No association with any real company, organization, product, person or event is intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation.

 

Microsoft may have patents, patent applications, trademarked, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property.

 

© Microsoft Corporation. All rights reserved.

 

Microsoft, MS-DOS, MS, Windows, Windows NT, MSDN, Active Directory, BizTalk, SQL Server, SharePoint, Outlook, PowerPoint, FrontPage, Visual Basic, Visual C++, Visual J++, Visual InterDev, Visual SourceSafe, Visual C#, Visual J#,  and Visual Studio are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A. and/or other countries.

 

Other product and company names herein may be the trademarks of their respective owners.


 

This source code is subject to terms and conditions of the Apache License, Version 2.0. A copy of the license can be found in the License.html file at the root of this distribution. If you cannot locate the Apache License, Version 2.0, please send an email to ironpy@microsoft.com. By using this source code in any fashion, you are agreeing to be bound by the terms of the Apache License, Version 2.0.

 

 

Comment Checker

A brief example which utilizes Microsoft Word to check the spelling of “#” style code comments.  The application will then display suggestions for misspelled words in a visually appealing manner via Microsoft’s Windows Presentation Foundation libraries.

 

Overview

One of the key benefits of programming in the Microsoft ecosystem is the wide breadth of existing libraries and tools available to the developer.  For example, included with every installation of Microsoft Office are .NET wrappers for Word/Excel/etc objects.  Not only do these wrappers allow one to generate Office documents programmatically, they also allow you to use features built directly into Office applications from your .NET application.  Just imagine for a moment what you could do with access to Word's spell checker.  Perhaps an English teacher would want to couple Office 2007's Optical Character Recognition (OCR) technology with spell checking to automatically grade students' essays.  The possibilities here are truly unlimited!

What could possibly make these Office libraries better?  Couple them one of the easiest, most productive programming languages on the planet today - Python.  In this sample/tutorial, not only will we show how to utilize Word's spell checking functionality from IronPython; we'll also use it to make our own Python code better!  You see, this sample processes Python files looking for code comments that contain misspellings.  Once these mistakes have been identified we utilize Word again to present you with the correct spellings.  All of this is tied together with an elegant, user-friendly interface constructed from .NET's Windows Presentation Framework.

Prerequisites

The prerequisites to successfully run the Comment Checker demo are:

Getting Started

Please make sure the sample folder, CommentChecker, (where this readme.htm is located) contains at least the following:

.\main.py
.\misspelled.py
.\spelling.py

HINT: if the folder containing the IronPython distribution is not already in your PATH environment variable, please add it from the command prompt you'll be working in.  By doing this you will be able to run the "ipy" command from any arbitrary directory:

set PATH=%PATH%;%ProgramFiles%\IronPython 2.6

 


Playing with the Pre-written Sample

From the command prompt, navigate to the CommentChecker directory and type the following:

> ipyw.exe main.py misspelled.py

 

This starts an IronPython Windows application that displays the misspelled.py file and highlights each spelling mistake inside code comments in a red background. If you click on any of the misspelled words, you'll be presented with a drop-down list of alternate spellings to use.  You can run Comment Checker against your own Python files as well by changing the second parameter passed to ipyw (e.g., misspelled.py in the command above).  The running application should look similar to the following:

CommentChecker Screenshot

 


Step-by-step Instructions on Implementing the Sample

While a fully implemented "comment checker" is already provided for your enjoyment (see previous section), you can discover exactly how it works by following this section which is deemed suitable for both Python/.NET beginners and experts.

Create a New Python File to Edit. 

3.      From a new Command Prompt window navigate to your favorite directory and please type:

notepad spelling.py

Note: Do not close the Command Prompt window as we’ll be using this later.

Note: From this point you should add Python code described in later steps to spelling.py.

4.      notepad should now start a new window and inform you that ‘spelling.py not found’.  When asked if you’d like to create this new file, click the Yes button.

Use the clr Module to Access MS Word APIs

1.      Add the following to spelling.py:

import clr

The import statement is used to import other Python modules.  The clr module is provided by IronPython to do Common Language Runtime oriented tasks such as adding .NET assembly references.

2.      Add the following to spelling.py:

clr.AddReferenceByPartialName("Microsoft.Office.Interop.Word")

from Microsoft.Office.Interop.Word import ApplicationClass

 

These two lines inject Microsoft Word’s ApplicationClass COM class into our namespace.

3.      Add the following to spelling.py:

ms_word = ApplicationClass()

ms_word.Documents.Add()

 

Here we create a global variable, ms_word, which is really an instance of the winword.exe process.  Also, we add a document to it so that we can get Word to offer spelling suggestions later on in this exercise.

Checkpoint

At this point your copy of spelling.py should be capable of displaying functionality provided by the Microsoft Word API:

1.      Save spelling.py in notepad by holding down the Ctrl key and pressing S once.

2.      From the Command Prompt started earlier in this exercise, start IronPython in interactive mode.  This is accomplished by running the following in the Command Prompt window:

ipy –i spelling.py

The “-i” flag tells IronPython to run in interactive mode.  The Python module specified after “-i” (e.g., spelling.py) will be automatically run and its contents injected into the global namespace.  In the Command Prompt you should now see the following:

>>> 

Note: If you cut and paste the ipy command above directly from your web browser into the Command Prompt, you may end up seeing an error message such as:

      File -i does not exist.

To get around this, simply type out the command by hand in the Command Prompt.

3.      Type:

dir(ms_word)

in the Command Prompt and press the Enter key.  You should now see all methods and properties Word provides us with.

4.      Type:

ms_word.Visible = True

 in the Command Prompt and press Enter.  Microsoft Word should open a new window.

5.      Type:

ms_word.Quit()

in the Command Prompt and press Enter.  This shuts down the new instance of Word.

6.      Hold down the Ctrl key and press Z in the Command Prompt.  Now press Enter to exit out of the interactive session.

Important Note: It’s advisable that you save your changes in notepad by pressing Ctrl+S after completing every section!

Check the Spelling of a Word

Add the following to spelling.py:

def check_word(x):

    return ms_word.CheckSpelling(x)

check_word returns True if Microsoft Word thinks the spelling of the input parameter, x, is correct.

Spelling Suggestions

Add the following to spelling.py:

def suggestions(x):

    res_objects = ms_word.GetSpellingSuggestions(x)

    return [y.Name for y in res_objects.GetEnumerator()]

The suggestions function asks MS Word for spelling suggestions of the misspelled word x.   It then returns these suggestions in the form of a Python list using list comprehension (i.e., the “[y.Name for y in …]” line).  Specifics about Python list comprehension are beyond the scope of this exercise, but you can learn more about them here - http://docs.python.org/tut/node7.html#SECTION007140000000000000000.

Checkpoint

1.      Save spelling.py in notepad.

2.      From the Command Prompt, run spelling.py in interactive mode again:

ipy –i spelling.py

3.      Play around with the functions you created:

>>> check_word("ab")

False

>>> suggestions("ab")

['abs', 'alb', 'am', 'an', 'as', 'at', 'a', 'bad', 'ad', 'ax']

>>> 

4.      Once you’re satisfied that the functions work as intended, press Ctrl+Z followed by Enter to exit out of the interactive session.

5.      You’ve now completed the first part of this exercise and may close notepad.

Create Another Python Module

1.      In the Command Prompt window please type:

notepad main.py

2.      notepad should now start a new window and inform you that ‘main.py not found’.  When asked if you’d like to create this new file, click the Yes button.

Note: From this point on you should add Python code described in later steps to main.py.

Open a Source File With “#”Style Comments

1.      Add the following to main.py:

import sys

import clr

from   spelling import *

sys is a standard CPython module which we use to access command-line parameters.  The clr module was described previously.  The third line above shows how to import all functions and global variables defined in the spelling.py module you created into main.py’s namespace.

2.      Add the following to main.py:

_temp_file = open(sys.argv[1], "r")

lines_in_file = _temp_file.readlines()

_temp_file.close()

This little snippet opens a file and stores all of its lines to a list/array called lines_in_file.  The name of the file is passed into IronPython from the command-line and obtained via the argv module attribute of sys.

Access Windows Presentation Foundation Types

Add the following to main.py:

clr.AddReferenceByPartialName("PresentationCore")

clr.AddReferenceByPartialName("PresentationFramework")

from System.Windows import Window, Application, HorizontalAlignment

from System.Windows.Controls import FlowDocumentScrollViewer, ComboBox

from System.Windows.Documents import FlowDocument, Paragraph, Run

from System.Windows.Media.Brushes import Black, PaleGreen, Red

Here we import various types from Microsoft’s Windows Presentation Foundation assemblies which we will later use to display our file.

Create a Window

1.      Add the following to main.py:

main_window = Window()

main_window.Title = "IronPython Comment Checker"

main_window.Background = Black

main_window.Foreground = PaleGreen

We’ve now created our main Window and set a few of its properties.

2.      Add the following text to main.py:

main_window.Content = FlowDocumentScrollViewer()

main_window.Content.Document = FlowDocument()

Our main_window object would not be very useful without any content attached to it.  For this reason we attach a document viewer which is used to dynamically display documents.

Generate a Paragraph

In this part of the exercise, we will add a function to create, populate, and return a Paragraph object which we will later add to the document.  This paragraph will consist of the entire file passed in from the command prompt (e.g., misspelled.py) with suggestions for all misspelled words in “#” style comments.

Add the following to main.py:

def create_paragraph(file_lines):

    #Create a "Paragraph" object to hold all text from the file

    paragraph = Paragraph()

    #Text in the paragraph will have a font size of 16

    paragraph.FontSize = 16.0

 

    #Go through every line in the file passed in from the command

    #line...

    for x in file_lines:

        #...looking for Python/Ruby/PowerShell style comments

        if "#" in x:

 

            #Split the line whenever a comment is found

            first, second = x.split("#", 1)

 

            #Add the first part of the line to the paragraph

            paragraph.Inlines.Add(Run(first + "#"))

           

            #Split the second part of the line based on whitespace

            for y in second.split():

                #If the word is misspelled...

                if not check_word(y):

                    #Add a drop down menu to offer alternative

                    #spelling suggestions

                    c = ComboBox()

                    c.Background = Red

                    c.HorizontalAlignment = HorizontalAlignment.Left

                    #Add the misspelled word to the drop down menu

                    #and make it the first item

                    c.AddText(y)

                    c.SelectedItem = y

                    #Offer alternative spellings in the drop down menu

                    for suggest in suggestions(y):

                        c.AddText(suggest)

                    #Add the combo box to the drop down menu

                    paragraph.Inlines.Add(c)

                else:

                    paragraph.Inlines.Add(Run(y))

                paragraph.Inlines.Add(" ")

            paragraph.Inlines.Add(Run("\n"))

        else:

            #If there's no comment in the line, just directly

            #add it to the paragraph

            paragraph.Inlines.Add(Run(x))

    return paragraph

Attach the Paragraph to the Document

Add the following to main.py:

main_window.Content.Document.Blocks.Add(create_paragraph(lines_in_file))

main_window.Show()

Application().Run()

ms_word.Quit()

 

Last but not least we:

1.      Add the paragraph created in the previous step to our document

2.      Make main_window visible by calling the Show method

3.      Call Application().Run() to begin accepting events and stop ipy.exe from exiting out of main.py until the end-user closes the window.

4.      Finally when the main window has finished running, we tell Microsoft Word to terminate.  Take note that this is the same ms_word object found in the spelling.py module.

Run Your Application

Now that you’ve finished coding this part of the exercise, it’s time to run it!  Due to the Application().Run() call made in the last step, you cannot pass the “-i” flag to ipy.  Instead you should call main.py using one of the following two patterns:

ipy main.py misspelled.py

or preferably:

            ipyw main.py misspelled.py

from the Command Prompt.  ipy is a console process and ipyw returns control immediately from the Command Prompt.  The second parameter to ipy/ipyw above, misspelled.py, is a file containing “#” style code comments and many misspelled words.  This file is denoted by “sys.argv[1]” in main.py.

 

This concludes our tutorial. Have fun playing with this sample!