I added some more tips to homework 9 in the comments section. I also corrected the get_wiki() function. Sorry about the inconvience there.
Here are the notes for today’s class covering more on python functions.
Most students did fairly well on this assignment. Please take a detailed look at my solution in resources/hmwk/hmwk8.py
mean | 49.71 |
---|---|
standard deviation | 9.2 |
-
Readability measures are used to score the reading difficulty of a text, for the purposes of selecting texts of appropriate difficulty for language learners. Let us define μw to be the average number of letters per word, and μs to be the average number of words per sentence, in a given text. The Automated Readability Index (ARI) of the text is defined to be: 4.71 μw + 0.5 μs – 21.43. Define a function which computes the ARI score. It should accept two arguments – the mean word length, and the mean sentence length. (5 points)
def calc_ari(mean_sent, mean_word):
ari = 4.71 * mean_word + 0.5 * mean_sent - 21.43
return(ari) -
One feature of English is that it is easy to turn verbs into nouns and adjectives, by using participles. For example, in the phrase the burning bush, the verb burn is used as an adjective, by using the present participle form. Create a function called verb_adjectives which uses the findall method from the NLTK to find present participles used as adjectives. For simplicity, find only adjectives that are preceded by an article (a, an, the). Make sure that they have a word following them (not punctuation). The function should accept a list of tokens, as returned by the words() function in the NLTK. Note that all present participles in English end in ing. Unfortunately, the nltk findall function which we used in class prints out the words, instead of just returning them. This means that we cannot use it in a function. (Go ahead and try to use it, and convince yourself why it is generally bad to print stuff from functions, instead of just returning results (unless the function’s only purpose is to print something out, e.g. pprint)). So, I will get you started on the functions you need to use:
regexp = r'<a><.*><man>' moby = nltk.Text( gutenberg .words('melville - moby_dick .txt ')) bracketed = nltk.text.TokenSearcher(moby) hits = bracketed.findall(regexp)
This returns a list of lists, where each list is composed of the 3 word phrase which matches. So your main task is to come up with the correct regular expression. (7 points)
def verb_adjectives(tokens):
'returns a list of 3-word phrases where a verb is used as an adjective'
regexp = r'<a|the><.*ing><\w+>'
bracketed = nltk.text.TokenSearcher(tokens)
hits = bracketed.findall(regexp)
return(hits) - As we have seen in class, most computational linguistics involves a combination of automation and hand-checking. Let’s refine our verb_adjectives function by ensuring that none of the words following the adjective are in the stopwords corpus. Without doing this, we get results like['an', 'understanding', 'of'], where understanding is being used as a noun, not an adjective. Use a list expression to remove all hits where the third word in the list is a stopword. (7 points)
def verb_adjectives(tokens):
'returns a list of 3-word phrases where a verb is used as an adjective'
regexp = r'<a|the><.*ing><\w+>'
bracketed = nltk.text.TokenSearcher(tokens)
hits = bracketed.findall(regexp)
eng_stop = nltk.corpus.stopwords.words('english')
hits = [h for h in hits if h[2].lower() not in eng_stop]
return(hits) - Add three more options to your script, -j (–adj), -a (–ari), and -n (–noheader). Note that if the –ari option is specified, then you should also print out the mean word length and mean sentence length. Your options should now look like:
-w --word print only mean word length -s --sent print only mean sentence length -h --help print this help information and exit -a --ari print ari statistics -j --adj print mean number of adjectival verbs per sentence -n --noheader do not print a header line
(10 points)
- Now modify your script so that it can accept either stdin or one or more files as input. Use the stdin_or_file() function in args.py as an example. Your script will no longer print out usage information when no arguments are given, as was the case for homework 7. Create a function called calc_text_stats to handle all the calculations. That way you can call this function either multiple times (once per file, if files are specified), or just once, if reading from stdin. This will make your code more readable. You should also make sure to handle the two new options, for ari and adj. (20 points)
def calc_text_stats(text, showsent, showword, showari, showadj):
'print out statistics for a raw text'
words = nltk.word_tokenize(text)
sents = sent_tokenize(text)
if showsent:
mean_sent_length = mean_sent_len(sents)
mean_sent_print = '%13.2f' % mean_sent_length
else:
mean_sent_print
if showword:
mean_word_length = mean_word_len(words)
mean_word_print = '%13.2f' % mean_word_length
else:
mean_word_print= ''
if showari:
ari = '%13.2f' % calc_ari(mean_sent_length, mean_word_length)
else:
ari=''
if showadj:
adjs = verb_adjectives(words)
mean_adjs = '%13.3f' % (len(adjs) / len(sents))
else:
mean_adjs=''
return '%s %s %s %s' % (mean_word_print,
mean_sent_print, ari, mean_adjs)
if showheader:
headers=['filename']
if showword:
headers.append('mean_word_len')
if showsent:
headers.append('mean_sent_len')
if showari:
headers.append('ari')
if showadj:
headers.append('adjectiv_verbs')
format_string = '%-17s ' + '%13s ' * (len(headers)-1)
print format_string % tuple(headers)
if len(args) > 0:
for file in args:
filename = os.path.basename(file).rstrip('.txt')
f = open(file)
raw = f.read()
print calc_text_stats(raw, showsent, showword, showari, showadj)
else:
raw = sys.stdin.read()
print calc_text_stats(raw, showsent, showword, showari, showadj) - Now print out the mean word length, mean sentence length, ari, and the mean number of present participles used as adjectives per sentence for huckFinn, tomSawyeer, Candide, and devilsDictionary. Pipe the output to sort, and sort by ari. Your output should be similar to homework 7. Show the BASH command you used. (11 points)
students/robfelty/hmwk8.py --noheader\
resources/texts/{huckFinn,tomSawyer,Candide,devilsDictionary}.txt | sort -nk 4
Here are the notes for today’s class covering a review of python basics, with special attention to collections and style.
In this homework, you will attempt to find novel words in webpages. Make
sure to read all questions before starting the assignment. It is due Oct. 30th
and covers material up to Oct. 22nd
-
Use the get_wiki function defined below to download the wikipedia page about Ben Franklin. (4 points)
def get_wiki(url): 'Download text from a wikipedia page and return raw text' from urllib2 import urlopen, Request headers = {'User-Agent': '''Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.0.4) Gecko/20060508 Firefox/1.5.0.4'''} req=Request(url=url, headers=headers) f = urlopen(req) raw = unicode(f.read(),encoding='utf8') return(raw)
- Wikipedia pages generally have a bunch of references and external links. These almost always occur at the section beginning “See also”. Strip off all text after “See also”. Hint: “See also” actually occurs twice in the document – once in the table of contents, and once as a section heading. You only want to ignore stuff after the section heading. (6 points)
-
Next, define a function called unknown, which removes any items from
this set that occur in the Words Corpus (nltk.corpus.words). The function should take a list of tokenized words as input, and return a list of novel words. Hint 1: your code
will be much faster if you convert the list of words in the Words Corpus into a
set, and then check whether or not a word is in that set. Hint 2: ignore case and punctuation when checking against the words corpus (but preserve case in your output). Hint 3: Sometimes the nltk word tokenizer does not strip off periods ending sentences. Make sure that none of the words end in a period. Hint 4: Make sure to strip out all html tags before tokenizing (see chapter 2 of the NLTK book for an example). (15 points) - Use your unknown function to find novel words in the wikipedia page on Ben Franklin (5 points)
- As with most computational linguistics processes, it is nearly impossible to achieve perfect results. It is clear from browsing through the results that there are a number of “novel” words, which in fact are not novel. Let’s further refine our process. Some of the “novel” words we have found may be numbers, proper names (named entities), acronyms, or words with affixes (including both inflectional and derivational affixes). Let’s try to divide up our novel words into these categories.
- Use regular expressions to remove any numbers from the novel words.
Remember that a number may have commas or a decimal point in it, and may begin
with a dollar sign or end with a percent sign. Save the result as
novel_nonum. Hint: when testing your regular expression, it is probaby
easier to check the result of finding items which are numbers, as opposed to
checking the result of finding items which are not numbers. (8 points) - Now Use the porter stemmer to stem all the items in novel_nonum, then re-run them through the unknown function, saving the result as as novel_stems (7 points)
- Next, find as many proper names from novel_stems as possible, saving the result as proper_names. Note that finding named entities is actually a very difficult problem, and usually involves syntax and semantics. For our purposes however, let’s just use the fact that proper names in English start with a capital letter. Also create a new variable novel_no_proper, which has the proper names removed. (5 points)
- Calculate the percentage of novel tokens in the Ben Franklin wikipedia page, after having excluded number, affixed words, and proper names. (4 points)
- Calculate the percentage of novel types in the Ben Franklin wikipedia page, after having excluded number, affixed words, and proper names. (6 points)
- Use regular expressions to remove any numbers from the novel words.
- Extra Credit: Find additional ways to remove false positives in our “novel” word list. (3 extra points for each additional way, up to 12 extra points)
Here are the notes for Oct 22nd, covering details of homework 7, more about string formatting, and more on integrating python with BASH and other common unix utilities.
Unfortunately my son is sick and cannot go to daycare tomorrow, so I have to cancel class. We will shift the syllabus back one day. Thursday we will talk more about strings, go over homework 7, and discuss shell integration.
This homework proved to be challenging for students. We will go over some of the common problems in class on Tuesday. Please take a detailed look at my solution in resources/hmwk
mean | 46 |
---|---|
standard deviation | 8.98 |
-
From BASH, use svn to copy your hmwk6.py file to hmwk7.py. This will preserve all of the history from hmwk6, so you can see how you have improved your code from homework 6 to homework 7. (3 points)
# in bash:
svn cp hmwk6.py hmwk7.py# Now in python
# we keep our functions from hmwk6
import sys
import os
import getopt
import string
from pprint import pprint
import nltk
from nltk.corpus import stopwords
def mean_sent_len(sents):
eng_stopwords = stopwords.words('english')
words_no_punc = [w for s in sents for w in s
if w not in string.punctuation and w.lower() not in eng_stopwords]
num_words = len(words_no_punc)
num_sents = len(sents)
return (num_words / num_sents)
def mean_word_len(words):
eng_stopwords = stopwords.words('english')
words_no_punc = [w for w in words
if w not in string.punctuation and w.lower() not in eng_stopwords]
num_words = len(words_no_punc)
num_chars = sum([len(w) for w in words_no_punc])
return (num_chars / num_words) - Create a function called usage, which prints out information about how the script should be used, including what arguments should be specified, and what options are possible. It should take one argument, which is the name of the script file. (7 points)
def usage(script):
print 'Usage: ' + script + ' <options> file(s)'
print '''
Possible options:
-w --word print only mean word length
-s --sent print only mean sentence length
-h --help print this help information and exit
''' - Write your script to process the following options. Look at opts.py under resources/py for an example. If both -s and -w are specified, it should print out both options. (14 points)
-w --word print only mean word length -s --sent print only mean sentence length -h --help print this help information and exit
try:
opts, args = getopt.gnu_getopt(sys.argv[1:], "hws",
["help", "word", "sent"])
except getopt.GetoptError, err:
# print help information and exit:
print str(err) # will print something like "option -a not recognized"
usage(sys.argv[0])
sys.exit(2)
sent = False
word = False
if len(opts) == 0:
sent = True
word = True
for o, a in opts:
if o in ("-h", "--help"):
usage(sys.argv[0])
sys.exit()
if o in ("-s", "--sent"):
sent = True
if o in ("-w", "--word"):
word = True -
Instead of specifying which texts to process in your code, change your code so
that it accepts filenames from the command line. Look at the args.py file
under resources/py for an example of how to do this. Your code should print out
the name of each file (you can use the os.path.basename function to print out only the name of the file) specified on the command line, and the mean word length
and sentence length, with a width of 13 and a precision of 2. Note that it
should only print word length or sentence length if that option has been
specified. If no files are specified, it should print the usage information
and exit. Also note that after reading in a text you will have to first convert
it to a list of words or sentences using the tokenize functions in the nltk,
before calculating the mean word length and sentence length with the functions
you defined in homework 6. See chapter 13 in the notes for examples on how to
tokenize text to homework 5 for how to do this. The first line of output should
be a line of headers describing the columns (28 points) Here is some example
output:filename mean_word_len mean_sent_len fooey 3.45 13.47 bar 3.15 9.29
if len(args) > 0:
if word and sent:
print '%-17s %s %s' % ('filename', 'mean_word_len', 'mean_sent_len')
elif word:
print '%-17s %s' % ('filename', 'mean_word_len')
elif sent:
print '%-17s %s' % ('filename', 'mean_sent_len')
for file in args:
f = open(file)
raw = f.read()
words = nltk.word_tokenize(raw)
sents = nltk.sent_tokenize(raw)
filename = os.path.basename(file).rstrip('.txt')
if sent:
mean_sent_length = mean_sent_len(sents)
if word:
mean_word_length = mean_word_len(words)
if word and sent:
print '%-17s %13.2f %13.2f' % (filename, mean_word_length, mean_sent_length)
elif word:
print '%-17s %13.2f' % (filename, mean_word_length)
elif sent:
print '%-17s %13.2f' % (filename, mean_sent_length)
else:
usage(sys.argv[0])
sys.exit(2) -
Use your script to print out mean word length and sentence length for huckFinn, tomSawyeer, Candide, and devilsDictionary (in resources/texts). Save the output to a file called hmwk7_stats.txt in your personal directory, and commit it to the svn repository. Show the command you use in BASH. Make your paths relative to the root of your working copy of the repository. Do the same command, but also try the -s and -w option, and print to the screen. (8 points)
# In bash:
students/robfelty/hmwk7.py resources/texts/{huckFinn,tomSawyer,Candide,devilsDictionary}.txt > students/robfelty/hmwk7_stats.txt
students/robfelty/hmwk7.py -w resources/texts/{huckFinn,tomSawyer,Candide,devilsDictionary}.txt
students/robfelty/hmwk7.py -s resources/texts/{huckFinn,tomSawyer,Candide,devilsDictionary}.txt
In this homework you will expand upon some of the code you wrote in homework 7, using the functions you wrote to calculate mean word and sentence length. However, you will now add the ability to read from stdin. Note that for this assignment, you should not print out any information about the questions. You should only print out information as requested in the last question. Make sure to read all questions before starting the assignment. It is due Oct. 23rd and covers material up to Oct. 15th.
- Readability measures are used to score the reading difficulty of a text, for the purposes of selecting texts of appropriate difficulty for language learners. Let us define μw to be the average number of letters per word, and μs to be the average number of words per sentence, in a given text. The Automated Readability Index (ARI) of the text is defined to be: 4.71 μw + 0.5 μs – 21.43. Define a function which computes the ARI score. It should accept two arguments – the mean word length, and the mean sentence length. (5 points)
-
One feature of English is that it is easy to turn verbs into nouns and adjectives, by using participles. For example, in the phrase the burning bush, the verb burn is used as an adjective, by using the present participle form. Create a function called verb_adjectives which uses the findall method from the NLTK to find present participles used as adjectives. For simplicity, find only adjectives that are preceded by an article (a, an, the). Make sure that they have a word following them (not punctuation). The function should accept a list of tokens, as returned by the words() function in the NLTK. Note that all present participles in English end in ing. Unfortunately, the nltk findall function which we used in class prints out the words, instead of just returning them. This means that we cannot use it in a function. (Go ahead and try to use it, and convince yourself why it is generally bad to print stuff from functions, instead of just returning results (unless the function’s only purpose is to print something out, e.g. pprint)). So, I will get you started on the functions you need to use:
regexp = r'<a><.*><man>' moby = nltk.Text( gutenberg .words('melville - moby_dick .txt ')) bracketed = nltk.text.TokenSearcher(moby) hits = bracketed.findall(regexp)
This returns a list of lists, where each list is composed of the 3 word phrase which matches. So your main task is to come up with the correct regular expression. (7 points)
- As we have seen in class, most computational linguistics involves a combination of automation and hand-checking. Let’s refine our verb_adjectives function by ensuring that none of the words following the adjective are in the stopwords corpus. Without doing this, we get results like['an', 'understanding', 'of'], where understanding is being used as a noun, not an adjective. Use a list expression to remove all hits where the third word in the list is a stopword. (7 points)
- Add three more options to your script, -j (–adj), -a (–ari), and -n (–noheader). Note that if the –ari option is specified, then you should also print out the mean word length and mean sentence length. If no options are given, it should function the same as if the options -wsaj were given. Your options should now look like:
-w --word print only mean word length -s --sent print only mean sentence length -h --help print this help information and exit -a --ari print ari statistics -j --adj print mean number of adjectival verbs per sentence -n --noheader do not print a header line
(10 points)
- Now modify your script so that it can accept either stdin or one or more files as input. Use the stdin_or_file() function in args.py as an example. Your script will no longer print out usage information when no arguments are given, as was the case for homework 7. Create a function called calc_text_stats to handle all the calculations. That way you can call this function either multiple times (once per file, if files are specified), or just once, if reading from stdin. This will make your code more readable. You should also make sure to handle the two new options, for ari and adj. (20 points)
- Now print out the mean word length, mean sentence length, ari, and the mean number of present participles used as adjectives per sentence for huckFinn, tomSawyeer, Candide, and devilsDictionary. Pipe the output to sort, and sort by ari. Your output should be similar to homework 7. Save the bash command you used in a script called ari. Make sure that it is executable. (11 points)