Info/CS 4300: Language and Information - in-class demo

Proto Information Retrieval System

We're going to build a very basic proto-IR system from scratch. In the first part we will preprocess the "documents" (in this case sentences from a Wikipedia article); in the second part we will implement a method for searching for the set of documents which are closest to a given query.

Basic text processing: sentences, types, tokens, similarity

In [1]:
from operator import itemgetter
In [2]:
import re
In [3]:
# Copy and pasted background info from the show's Wikipedia page
# (http://en.wikipedia.org/wiki/Keeping_Up_with_the_Kardashians)

background = u"""
Robert Kardashian (1944-2003) and Kristen Mary "Kris" Houghton (born 1955) married in 1978 and had four children together, daughters Kourtney (born 1979), Kim (born 1980), and Khloé, (born 1984), and son Rob (born 1987). The couple divorced in 1991.[3] In 1994, Robert entered the media spotlight when he defended O.J. Simpson for the murders of Nicole Brown Simpson and Ronald Goldman during a lengthy trial. Kris married former Olympic champion Bruce Jenner (born 1949) in 1991. Bruce and Kris had two daughters together, Kendall (born 1995) and Kylie (born 1997). Robert died in 2003 eight weeks after being diagnosed with esophageal cancer.[4] In 2004, Kim became a personal stylist to recording artist Brandy Norwood; she eventually developed into a full-time stylist, and was a personal shopper and stylist to actress Lindsay Lohan.[5] Khloé, Kim and Kourtney further ventured into fashion, opening a high fashion boutique D-A-S-H in Calabasas, California. Throughout Kim's early career, she involved herself in some high-profile relationships including Norwood's brother, rapper Ray J and later, singer Nick Lachey.[5] In 2006, Kourtney starred in her first reality television series, Filthy Rich: Cattle Drive.[6] In February 2007, a home sex video that Kim made with Ray J years earlier was leaked.[7] Vivid Entertainment bought the rights for $1 million and released the film as Kim Kardashian: Superstar on February 21.[7] Kim sued Vivid for ownership of the tape, but dropped the suit in April 2007 and settled with Vivid Entertainment for $5 million.[8]

In August 2007, it was announced that the Kardashians and Jenners would star in a yet-to-be-titled reality show on E!, with Ryan Seacrest serving as executive producer.[6] Seacrest said "At the heart of the series—despite the catfights and endless sarcasm—is a family that truly loves and supports one another [...] The familiar dynamics of this family make them one Hollywood bunch that is sure to entertain." The series announcement came one week after Paris Hilton and her friend Nicole Richie announced that their popular E! series entitled The Simple Life was ending.[6] Keeping Up With the Kardashians premiered on October 14, 2007.[9]

On November 13, 2007, it was announced that E! renewed the show for its second season.[9] The following year, it was renewed for a third season. Lisa Berger, executive vice president of original programming and series development for the network, said "viewers have embraced the Kardashian family and the series has become one of television's most-talked-about shows [...] We are fortunate to work with Seacrest and Bunim-Murray, which have an exceptional ability to capture the Kardashians' hilarious, chaotic and always entertaining personalities and family dynamics."[10] The Hollywood Reporter reported that the family made an estimated $65 million throughout 2010.[3]

In 2011, Kim married NBA player Kris Humphries in a highly publicized wedding ceremony,[11] but filed for divorce 72 days later.[12] This caused widespread backlash from the public and media.[13] Several news outlets surmised that Kardashian's marriage to Humphries was merely a publicity stunt, to promote the Kardashian family's brand and their subsequent television ventures.[14] A widely circulated petition asking to remove all Kardashian-related programming from the air has followed since their split.[15] As of December 2013, eight seasons of the series have aired. On April 24, 2012, E! signed a three-year deal with the Kardashian family that will keep the series airing through seasons seven, eight and nine.[16] The deal was estimated at $40 million.[17][18] On January. 4, 2015, a tenth season was announced to premiere on Feb 8, 2015 after the Kourtney and Khloé Take The Hamptons season finale.

The show revolves around the children of Kris Jenner, and originally focused on her children from her first marriage to deceased attorney Robert Kardashian: Kourtney, Kim, Khloé, and Rob Kourtney's boyfriend Scott Disick is a main character on the show. As the series progressed, Kris' children Kendall and Kylie also became recurring cast members of the show. Kris' second husband[19] 1976 Summer Olympics decathlon champion Bruce Jenner, is also frequently featured on the show, and has been a recurring cast member since the show began.
Since the series' premiere, the Kardashian sisters have established careers in the fashion industry, co-owning the fashion boutique D-A-S-H and launching several fragrances and clothing collections.
Kim gained notoriety as the subject of a sex tape in 2007, and later became involved in a relationship with New Orleans Saints running back Reggie Bush from 2007- March 2010.[20] In 2011, she received widespread criticism after filing for divorce from New Jersey Nets power forward Kris Humphries after a 72-day marriage. In 2012, while still married Kim became pregnant by rapper Kanye West; after suffering from preeclampsia she gave birth prematurely to their daughter North the following June.
Khloé attained notoriety in her own right after being arrested for driving under the influence in 2007, for which she was jailed for approximately three hours in 2008. The following year (during the fourth season), she married Los Angeles Lakers forward Lamar Odom after a one-month relationship. In 2012, she served as a co-host during the second season of the American version of The X Factor.
Rob launched the sock line "Arthur George" in 2012, and was involved in a relationship with singer Adrienne Bailon in the second and third seasons.
Kendall and Kylie have also established careers in the modeling industry.
In the eighth season, Bruce's sons Brandon and Brody Jenner, and Brandon's wife Leah Felder (daughter of Eagles band member Don Felder), were integrated into the supporting cast, while Kourtney, Khloé, and Kim's friends Malika Haqq and Jonathan Cheban joined the series in the second and third seasons.
The family earns an alleged total of $10 million per season of the series.[21]"""

We want to work with sentences. A simple idea is to break at periods.

In [4]:
background.split(".")
Out[4]:
['\nRobert Kardashian (1944-2003) and Kristen Mary "Kris" Houghton (born 1955) married in 1978 and had four children together, daughters Kourtney (born 1979), Kim (born 1980), and Khloé, (born 1984), and son Rob (born 1987)',
 ' The couple divorced in 1991',
 '[3] In 1994, Robert entered the media spotlight when he defended O',
 'J',
 ' Simpson for the murders of Nicole Brown Simpson and Ronald Goldman during a lengthy trial',
 ' Kris married former Olympic champion Bruce Jenner (born 1949) in 1991',
 ' Bruce and Kris had two daughters together, Kendall (born 1995) and Kylie (born 1997)',
 ' Robert died in 2003 eight weeks after being diagnosed with esophageal cancer',
 '[4] In 2004, Kim became a personal stylist to recording artist Brandy Norwood; she eventually developed into a full-time stylist, and was a personal shopper and stylist to actress Lindsay Lohan',
 '[5] Khloé, Kim and Kourtney further ventured into fashion, opening a high fashion boutique D-A-S-H in Calabasas, California',
 " Throughout Kim's early career, she involved herself in some high-profile relationships including Norwood's brother, rapper Ray J and later, singer Nick Lachey",
 '[5] In 2006, Kourtney starred in her first reality television series, Filthy Rich: Cattle Drive',
 '[6] In February 2007, a home sex video that Kim made with Ray J years earlier was leaked',
 '[7] Vivid Entertainment bought the rights for $1 million and released the film as Kim Kardashian: Superstar on February 21',
 '[7] Kim sued Vivid for ownership of the tape, but dropped the suit in April 2007 and settled with Vivid Entertainment for $5 million',
 '[8]\n\nIn August 2007, it was announced that the Kardashians and Jenners would star in a yet-to-be-titled reality show on E!, with Ryan Seacrest serving as executive producer',
 '[6] Seacrest said "At the heart of the series—despite the catfights and endless sarcasm—is a family that truly loves and supports one another [',
 '',
 '',
 '] The familiar dynamics of this family make them one Hollywood bunch that is sure to entertain',
 '" The series announcement came one week after Paris Hilton and her friend Nicole Richie announced that their popular E! series entitled The Simple Life was ending',
 '[6] Keeping Up With the Kardashians premiered on October 14, 2007',
 '[9]\n\nOn November 13, 2007, it was announced that E! renewed the show for its second season',
 '[9] The following year, it was renewed for a third season',
 ' Lisa Berger, executive vice president of original programming and series development for the network, said "viewers have embraced the Kardashian family and the series has become one of television\'s most-talked-about shows [',
 '',
 '',
 "] We are fortunate to work with Seacrest and Bunim-Murray, which have an exceptional ability to capture the Kardashians' hilarious, chaotic and always entertaining personalities and family dynamics",
 '"[10] The Hollywood Reporter reported that the family made an estimated $65 million throughout 2010',
 '[3]\n\nIn 2011, Kim married NBA player Kris Humphries in a highly publicized wedding ceremony,[11] but filed for divorce 72 days later',
 '[12] This caused widespread backlash from the public and media',
 "[13] Several news outlets surmised that Kardashian's marriage to Humphries was merely a publicity stunt, to promote the Kardashian family's brand and their subsequent television ventures",
 '[14] A widely circulated petition asking to remove all Kardashian-related programming from the air has followed since their split',
 '[15] As of December 2013, eight seasons of the series have aired',
 ' On April 24, 2012, E! signed a three-year deal with the Kardashian family that will keep the series airing through seasons seven, eight and nine',
 '[16] The deal was estimated at $40 million',
 '[17][18] On January',
 ' 4, 2015, a tenth season was announced to premiere on Feb 8, 2015 after the Kourtney and Khloé Take The Hamptons season finale',
 "\n\nThe show revolves around the children of Kris Jenner, and originally focused on her children from her first marriage to deceased attorney Robert Kardashian: Kourtney, Kim, Khloé, and Rob Kourtney's boyfriend Scott Disick is a main character on the show",
 " As the series progressed, Kris' children Kendall and Kylie also became recurring cast members of the show",
 " Kris' second husband[19] 1976 Summer Olympics decathlon champion Bruce Jenner, is also frequently featured on the show, and has been a recurring cast member since the show began",
 "\nSince the series' premiere, the Kardashian sisters have established careers in the fashion industry, co-owning the fashion boutique D-A-S-H and launching several fragrances and clothing collections",
 '\nKim gained notoriety as the subject of a sex tape in 2007, and later became involved in a relationship with New Orleans Saints running back Reggie Bush from 2007- March 2010',
 '[20] In 2011, she received widespread criticism after filing for divorce from New Jersey Nets power forward Kris Humphries after a 72-day marriage',
 ' In 2012, while still married Kim became pregnant by rapper Kanye West; after suffering from preeclampsia she gave birth prematurely to their daughter North the following June',
 '\nKhloé attained notoriety in her own right after being arrested for driving under the influence in 2007, for which she was jailed for approximately three hours in 2008',
 ' The following year (during the fourth season), she married Los Angeles Lakers forward Lamar Odom after a one-month relationship',
 ' In 2012, she served as a co-host during the second season of the American version of The X Factor',
 '\nRob launched the sock line "Arthur George" in 2012, and was involved in a relationship with singer Adrienne Bailon in the second and third seasons',
 '\nKendall and Kylie have also established careers in the modeling industry',
 "\nIn the eighth season, Bruce's sons Brandon and Brody Jenner, and Brandon's wife Leah Felder (daughter of Eagles band member Don Felder), were integrated into the supporting cast, while Kourtney, Khloé, and Kim's friends Malika Haqq and Jonathan Cheban joined the series in the second and third seasons",
 '\nThe family earns an alleged total of $10 million per season of the series',
 '[21]']

This is not perfect . One problem consists of the Wikipedia footnotes such as "[9]", which are irrelevant to us. Let's remove them with a regular expression.

In [5]:
re.findall(r"\[\d+\]", background)
Out[5]:
['[3]',
 '[4]',
 '[5]',
 '[5]',
 '[6]',
 '[7]',
 '[7]',
 '[8]',
 '[6]',
 '[6]',
 '[9]',
 '[9]',
 '[10]',
 '[3]',
 '[11]',
 '[12]',
 '[13]',
 '[14]',
 '[15]',
 '[16]',
 '[17]',
 '[18]',
 '[19]',
 '[20]',
 '[21]']
In [6]:
background_nofoot = re.sub(r"\[\d+\]", "", background)
background_nofoot
Out[6]:
'\nRobert Kardashian (1944-2003) and Kristen Mary "Kris" Houghton (born 1955) married in 1978 and had four children together, daughters Kourtney (born 1979), Kim (born 1980), and Khloé, (born 1984), and son Rob (born 1987). The couple divorced in 1991. In 1994, Robert entered the media spotlight when he defended O.J. Simpson for the murders of Nicole Brown Simpson and Ronald Goldman during a lengthy trial. Kris married former Olympic champion Bruce Jenner (born 1949) in 1991. Bruce and Kris had two daughters together, Kendall (born 1995) and Kylie (born 1997). Robert died in 2003 eight weeks after being diagnosed with esophageal cancer. In 2004, Kim became a personal stylist to recording artist Brandy Norwood; she eventually developed into a full-time stylist, and was a personal shopper and stylist to actress Lindsay Lohan. Khloé, Kim and Kourtney further ventured into fashion, opening a high fashion boutique D-A-S-H in Calabasas, California. Throughout Kim\'s early career, she involved herself in some high-profile relationships including Norwood\'s brother, rapper Ray J and later, singer Nick Lachey. In 2006, Kourtney starred in her first reality television series, Filthy Rich: Cattle Drive. In February 2007, a home sex video that Kim made with Ray J years earlier was leaked. Vivid Entertainment bought the rights for $1 million and released the film as Kim Kardashian: Superstar on February 21. Kim sued Vivid for ownership of the tape, but dropped the suit in April 2007 and settled with Vivid Entertainment for $5 million.\n\nIn August 2007, it was announced that the Kardashians and Jenners would star in a yet-to-be-titled reality show on E!, with Ryan Seacrest serving as executive producer. Seacrest said "At the heart of the series—despite the catfights and endless sarcasm—is a family that truly loves and supports one another [...] The familiar dynamics of this family make them one Hollywood bunch that is sure to entertain." The series announcement came one week after Paris Hilton and her friend Nicole Richie announced that their popular E! series entitled The Simple Life was ending. Keeping Up With the Kardashians premiered on October 14, 2007.\n\nOn November 13, 2007, it was announced that E! renewed the show for its second season. The following year, it was renewed for a third season. Lisa Berger, executive vice president of original programming and series development for the network, said "viewers have embraced the Kardashian family and the series has become one of television\'s most-talked-about shows [...] We are fortunate to work with Seacrest and Bunim-Murray, which have an exceptional ability to capture the Kardashians\' hilarious, chaotic and always entertaining personalities and family dynamics." The Hollywood Reporter reported that the family made an estimated $65 million throughout 2010.\n\nIn 2011, Kim married NBA player Kris Humphries in a highly publicized wedding ceremony, but filed for divorce 72 days later. This caused widespread backlash from the public and media. Several news outlets surmised that Kardashian\'s marriage to Humphries was merely a publicity stunt, to promote the Kardashian family\'s brand and their subsequent television ventures. A widely circulated petition asking to remove all Kardashian-related programming from the air has followed since their split. As of December 2013, eight seasons of the series have aired. On April 24, 2012, E! signed a three-year deal with the Kardashian family that will keep the series airing through seasons seven, eight and nine. The deal was estimated at $40 million. On January. 4, 2015, a tenth season was announced to premiere on Feb 8, 2015 after the Kourtney and Khloé Take The Hamptons season finale.\n\nThe show revolves around the children of Kris Jenner, and originally focused on her children from her first marriage to deceased attorney Robert Kardashian: Kourtney, Kim, Khloé, and Rob Kourtney\'s boyfriend Scott Disick is a main character on the show. As the series progressed, Kris\' children Kendall and Kylie also became recurring cast members of the show. Kris\' second husband 1976 Summer Olympics decathlon champion Bruce Jenner, is also frequently featured on the show, and has been a recurring cast member since the show began.\nSince the series\' premiere, the Kardashian sisters have established careers in the fashion industry, co-owning the fashion boutique D-A-S-H and launching several fragrances and clothing collections.\nKim gained notoriety as the subject of a sex tape in 2007, and later became involved in a relationship with New Orleans Saints running back Reggie Bush from 2007- March 2010. In 2011, she received widespread criticism after filing for divorce from New Jersey Nets power forward Kris Humphries after a 72-day marriage. In 2012, while still married Kim became pregnant by rapper Kanye West; after suffering from preeclampsia she gave birth prematurely to their daughter North the following June.\nKhloé attained notoriety in her own right after being arrested for driving under the influence in 2007, for which she was jailed for approximately three hours in 2008. The following year (during the fourth season), she married Los Angeles Lakers forward Lamar Odom after a one-month relationship. In 2012, she served as a co-host during the second season of the American version of The X Factor.\nRob launched the sock line "Arthur George" in 2012, and was involved in a relationship with singer Adrienne Bailon in the second and third seasons.\nKendall and Kylie have also established careers in the modeling industry.\nIn the eighth season, Bruce\'s sons Brandon and Brody Jenner, and Brandon\'s wife Leah Felder (daughter of Eagles band member Don Felder), were integrated into the supporting cast, while Kourtney, Khloé, and Kim\'s friends Malika Haqq and Jonathan Cheban joined the series in the second and third seasons.\nThe family earns an alleged total of $10 million per season of the series.'

We can now try to split sentences again. We also want to split on other punctuation marks, not just the period. This is possible with regular expressions.

In [7]:
splitter = re.compile(r"""
    [.!?]       # split on punctuation
    """, re.VERBOSE)

for sent in splitter.split(background_nofoot):
    print(sent.strip())
    print("--")
Robert Kardashian (1944-2003) and Kristen Mary "Kris" Houghton (born 1955) married in 1978 and had four children together, daughters Kourtney (born 1979), Kim (born 1980), and Khloé, (born 1984), and son Rob (born 1987)
--
The couple divorced in 1991
--
In 1994, Robert entered the media spotlight when he defended O
--
J
--
Simpson for the murders of Nicole Brown Simpson and Ronald Goldman during a lengthy trial
--
Kris married former Olympic champion Bruce Jenner (born 1949) in 1991
--
Bruce and Kris had two daughters together, Kendall (born 1995) and Kylie (born 1997)
--
Robert died in 2003 eight weeks after being diagnosed with esophageal cancer
--
In 2004, Kim became a personal stylist to recording artist Brandy Norwood; she eventually developed into a full-time stylist, and was a personal shopper and stylist to actress Lindsay Lohan
--
Khloé, Kim and Kourtney further ventured into fashion, opening a high fashion boutique D-A-S-H in Calabasas, California
--
Throughout Kim's early career, she involved herself in some high-profile relationships including Norwood's brother, rapper Ray J and later, singer Nick Lachey
--
In 2006, Kourtney starred in her first reality television series, Filthy Rich: Cattle Drive
--
In February 2007, a home sex video that Kim made with Ray J years earlier was leaked
--
Vivid Entertainment bought the rights for $1 million and released the film as Kim Kardashian: Superstar on February 21
--
Kim sued Vivid for ownership of the tape, but dropped the suit in April 2007 and settled with Vivid Entertainment for $5 million
--
In August 2007, it was announced that the Kardashians and Jenners would star in a yet-to-be-titled reality show on E
--
, with Ryan Seacrest serving as executive producer
--
Seacrest said "At the heart of the series—despite the catfights and endless sarcasm—is a family that truly loves and supports one another [
--

--

--
] The familiar dynamics of this family make them one Hollywood bunch that is sure to entertain
--
" The series announcement came one week after Paris Hilton and her friend Nicole Richie announced that their popular E
--
series entitled The Simple Life was ending
--
Keeping Up With the Kardashians premiered on October 14, 2007
--
On November 13, 2007, it was announced that E
--
renewed the show for its second season
--
The following year, it was renewed for a third season
--
Lisa Berger, executive vice president of original programming and series development for the network, said "viewers have embraced the Kardashian family and the series has become one of television's most-talked-about shows [
--

--

--
] We are fortunate to work with Seacrest and Bunim-Murray, which have an exceptional ability to capture the Kardashians' hilarious, chaotic and always entertaining personalities and family dynamics
--
" The Hollywood Reporter reported that the family made an estimated $65 million throughout 2010
--
In 2011, Kim married NBA player Kris Humphries in a highly publicized wedding ceremony, but filed for divorce 72 days later
--
This caused widespread backlash from the public and media
--
Several news outlets surmised that Kardashian's marriage to Humphries was merely a publicity stunt, to promote the Kardashian family's brand and their subsequent television ventures
--
A widely circulated petition asking to remove all Kardashian-related programming from the air has followed since their split
--
As of December 2013, eight seasons of the series have aired
--
On April 24, 2012, E
--
signed a three-year deal with the Kardashian family that will keep the series airing through seasons seven, eight and nine
--
The deal was estimated at $40 million
--
On January
--
4, 2015, a tenth season was announced to premiere on Feb 8, 2015 after the Kourtney and Khloé Take The Hamptons season finale
--
The show revolves around the children of Kris Jenner, and originally focused on her children from her first marriage to deceased attorney Robert Kardashian: Kourtney, Kim, Khloé, and Rob Kourtney's boyfriend Scott Disick is a main character on the show
--
As the series progressed, Kris' children Kendall and Kylie also became recurring cast members of the show
--
Kris' second husband 1976 Summer Olympics decathlon champion Bruce Jenner, is also frequently featured on the show, and has been a recurring cast member since the show began
--
Since the series' premiere, the Kardashian sisters have established careers in the fashion industry, co-owning the fashion boutique D-A-S-H and launching several fragrances and clothing collections
--
Kim gained notoriety as the subject of a sex tape in 2007, and later became involved in a relationship with New Orleans Saints running back Reggie Bush from 2007- March 2010
--
In 2011, she received widespread criticism after filing for divorce from New Jersey Nets power forward Kris Humphries after a 72-day marriage
--
In 2012, while still married Kim became pregnant by rapper Kanye West; after suffering from preeclampsia she gave birth prematurely to their daughter North the following June
--
Khloé attained notoriety in her own right after being arrested for driving under the influence in 2007, for which she was jailed for approximately three hours in 2008
--
The following year (during the fourth season), she married Los Angeles Lakers forward Lamar Odom after a one-month relationship
--
In 2012, she served as a co-host during the second season of the American version of The X Factor
--
Rob launched the sock line "Arthur George" in 2012, and was involved in a relationship with singer Adrienne Bailon in the second and third seasons
--
Kendall and Kylie have also established careers in the modeling industry
--
In the eighth season, Bruce's sons Brandon and Brody Jenner, and Brandon's wife Leah Felder (daughter of Eagles band member Don Felder), were integrated into the supporting cast, while Kourtney, Khloé, and Kim's friends Malika Haqq and Jonathan Cheban joined the series in the second and third seasons
--
The family earns an alleged total of $10 million per season of the series
--

--

While this looks better, it messes up som instances: O.J. Simpson's name, the "E!" network's name, and ellipses (...).

To deal with this, we need to think about the decision process of whether a punctuation mark is an end of sentence or not. In class, we came up with three requirements:

  • It is succeeded by at least one whitespace character (discards O.J)
  • The first character after the whitespace should be uppercase (discards E! renewed)
  • The last character before it should not be uppercase (discards J. Simpson)

Are these rules complete?

In [8]:
#Note that I do not need to catch the last sentence ending, since I am using split.


splitter = re.compile(r"""
    (?<![A-Z])  # LOOKBEHIND last character cannot be uppercase
    [.!?]       # match punctuation
    \s+
    (?=[A-Z])   # LOOKAHEAD next character must be followed by at least one whitespace and an uppercase      
    """, re.VERBOSE)

# But if I really really want to match that last period (note that this will create and extra empty sentence)
# splitter = re.compile(r"""
#     (?<![A-Z])  # LOOKBEHIND last character cannot be uppercase
#     [.!?]       # match punctuation
#     (?=         # LOOKAHEAD next character must either be:
#     \s+[A-Z]    # followed by at least one whitespace and an uppercase
#     |
#     \s*$        # followed by the end of the string
#     )           
#     """, re.VERBOSE)

Running our sentence splitter on the text, it seems to do a good job.

In [9]:
for sentence in splitter.split(background_nofoot):
    print(sentence.strip())
    print("--")
Robert Kardashian (1944-2003) and Kristen Mary "Kris" Houghton (born 1955) married in 1978 and had four children together, daughters Kourtney (born 1979), Kim (born 1980), and Khloé, (born 1984), and son Rob (born 1987)
--
The couple divorced in 1991
--
In 1994, Robert entered the media spotlight when he defended O.J. Simpson for the murders of Nicole Brown Simpson and Ronald Goldman during a lengthy trial
--
Kris married former Olympic champion Bruce Jenner (born 1949) in 1991
--
Bruce and Kris had two daughters together, Kendall (born 1995) and Kylie (born 1997)
--
Robert died in 2003 eight weeks after being diagnosed with esophageal cancer
--
In 2004, Kim became a personal stylist to recording artist Brandy Norwood; she eventually developed into a full-time stylist, and was a personal shopper and stylist to actress Lindsay Lohan
--
Khloé, Kim and Kourtney further ventured into fashion, opening a high fashion boutique D-A-S-H in Calabasas, California
--
Throughout Kim's early career, she involved herself in some high-profile relationships including Norwood's brother, rapper Ray J and later, singer Nick Lachey
--
In 2006, Kourtney starred in her first reality television series, Filthy Rich: Cattle Drive
--
In February 2007, a home sex video that Kim made with Ray J years earlier was leaked
--
Vivid Entertainment bought the rights for $1 million and released the film as Kim Kardashian: Superstar on February 21
--
Kim sued Vivid for ownership of the tape, but dropped the suit in April 2007 and settled with Vivid Entertainment for $5 million
--
In August 2007, it was announced that the Kardashians and Jenners would star in a yet-to-be-titled reality show on E!, with Ryan Seacrest serving as executive producer
--
Seacrest said "At the heart of the series—despite the catfights and endless sarcasm—is a family that truly loves and supports one another [...] The familiar dynamics of this family make them one Hollywood bunch that is sure to entertain." The series announcement came one week after Paris Hilton and her friend Nicole Richie announced that their popular E! series entitled The Simple Life was ending
--
Keeping Up With the Kardashians premiered on October 14, 2007
--
On November 13, 2007, it was announced that E! renewed the show for its second season
--
The following year, it was renewed for a third season
--
Lisa Berger, executive vice president of original programming and series development for the network, said "viewers have embraced the Kardashian family and the series has become one of television's most-talked-about shows [...] We are fortunate to work with Seacrest and Bunim-Murray, which have an exceptional ability to capture the Kardashians' hilarious, chaotic and always entertaining personalities and family dynamics." The Hollywood Reporter reported that the family made an estimated $65 million throughout 2010
--
In 2011, Kim married NBA player Kris Humphries in a highly publicized wedding ceremony, but filed for divorce 72 days later
--
This caused widespread backlash from the public and media
--
Several news outlets surmised that Kardashian's marriage to Humphries was merely a publicity stunt, to promote the Kardashian family's brand and their subsequent television ventures
--
A widely circulated petition asking to remove all Kardashian-related programming from the air has followed since their split
--
As of December 2013, eight seasons of the series have aired
--
On April 24, 2012, E! signed a three-year deal with the Kardashian family that will keep the series airing through seasons seven, eight and nine
--
The deal was estimated at $40 million
--
On January. 4, 2015, a tenth season was announced to premiere on Feb 8, 2015 after the Kourtney and Khloé Take The Hamptons season finale
--
The show revolves around the children of Kris Jenner, and originally focused on her children from her first marriage to deceased attorney Robert Kardashian: Kourtney, Kim, Khloé, and Rob Kourtney's boyfriend Scott Disick is a main character on the show
--
As the series progressed, Kris' children Kendall and Kylie also became recurring cast members of the show
--
Kris' second husband 1976 Summer Olympics decathlon champion Bruce Jenner, is also frequently featured on the show, and has been a recurring cast member since the show began
--
Since the series' premiere, the Kardashian sisters have established careers in the fashion industry, co-owning the fashion boutique D-A-S-H and launching several fragrances and clothing collections
--
Kim gained notoriety as the subject of a sex tape in 2007, and later became involved in a relationship with New Orleans Saints running back Reggie Bush from 2007- March 2010
--
In 2011, she received widespread criticism after filing for divorce from New Jersey Nets power forward Kris Humphries after a 72-day marriage
--
In 2012, while still married Kim became pregnant by rapper Kanye West; after suffering from preeclampsia she gave birth prematurely to their daughter North the following June
--
Khloé attained notoriety in her own right after being arrested for driving under the influence in 2007, for which she was jailed for approximately three hours in 2008
--
The following year (during the fourth season), she married Los Angeles Lakers forward Lamar Odom after a one-month relationship
--
In 2012, she served as a co-host during the second season of the American version of The X Factor
--
Rob launched the sock line "Arthur George" in 2012, and was involved in a relationship with singer Adrienne Bailon in the second and third seasons
--
Kendall and Kylie have also established careers in the modeling industry
--
In the eighth season, Bruce's sons Brandon and Brody Jenner, and Brandon's wife Leah Felder (daughter of Eagles band member Don Felder), were integrated into the supporting cast, while Kourtney, Khloé, and Kim's friends Malika Haqq and Jonathan Cheban joined the series in the second and third seasons
--
The family earns an alleged total of $10 million per season of the series.
--

Now let's identify individual words within each sentence. Rather than splitting at whitespace, let's match all sequences of word characters.

In [34]:
word_splitter = re.compile(r"""
    (\w+)
    """, re.VERBOSE)
In [35]:
def getwords(sent):
    return [w.lower() 
            for w in word_splitter.findall(sent)]

sent_words_lower = [getwords(sent) 
                    for sent in splitter.split(background_nofoot)]

How many sentences do we have?

In [36]:
len(sent_words_lower)
Out[36]:
41

How many words are there in total? ("tokens")

In [15]:
allwords=[w for sent in sent_words_lower
          for w in sent]
In [16]:
sorted(allwords)
Out[16]:
['1',
 '10',
 '13',
 '14',
 '1944',
 '1949',
 '1955',
 '1976',
 '1978',
 '1979',
 '1980',
 '1984',
 '1987',
 '1991',
 '1991',
 '1994',
 '1995',
 '1997',
 '2003',
 '2003',
 '2004',
 '2006',
 '2007',
 '2007',
 '2007',
 '2007',
 '2007',
 '2007',
 '2007',
 '2007',
 '2008',
 '2010',
 '2010',
 '2011',
 '2011',
 '2012',
 '2012',
 '2012',
 '2012',
 '2013',
 '2015',
 '2015',
 '21',
 '24',
 '4',
 '40',
 '5',
 '65',
 '72',
 '72',
 '8',
 'a',
 'a',
 'a',
 'a',
 'a',
 'a',
 'a',
 'a',
 'a',
 'a',
 'a',
 'a',
 'a',
 'a',
 'a',
 'a',
 'a',
 'a',
 'a',
 'a',
 'a',
 'a',
 'a',
 'a',
 'ability',
 'about',
 'actress',
 'adrienne',
 'after',
 'after',
 'after',
 'after',
 'after',
 'after',
 'after',
 'after',
 'air',
 'aired',
 'airing',
 'all',
 'alleged',
 'also',
 'also',
 'also',
 'always',
 'american',
 'an',
 'an',
 'an',
 'and',
 'and',
 'and',
 'and',
 'and',
 'and',
 'and',
 'and',
 'and',
 'and',
 'and',
 'and',
 'and',
 'and',
 'and',
 'and',
 'and',
 'and',
 'and',
 'and',
 'and',
 'and',
 'and',
 'and',
 'and',
 'and',
 'and',
 'and',
 'and',
 'and',
 'and',
 'and',
 'and',
 'and',
 'and',
 'and',
 'and',
 'and',
 'and',
 'and',
 'and',
 'angeles',
 'announced',
 'announced',
 'announced',
 'announced',
 'announcement',
 'another',
 'approximately',
 'april',
 'april',
 'are',
 'around',
 'arrested',
 'arthur',
 'artist',
 'as',
 'as',
 'as',
 'as',
 'as',
 'as',
 'asking',
 'at',
 'at',
 'attained',
 'attorney',
 'august',
 'back',
 'backlash',
 'bailon',
 'band',
 'be',
 'became',
 'became',
 'became',
 'became',
 'become',
 'been',
 'began',
 'being',
 'being',
 'berger',
 'birth',
 'born',
 'born',
 'born',
 'born',
 'born',
 'born',
 'born',
 'born',
 'bought',
 'boutique',
 'boutique',
 'boyfriend',
 'brand',
 'brandon',
 'brandon',
 'brandy',
 'brody',
 'brother',
 'brown',
 'bruce',
 'bruce',
 'bruce',
 'bruce',
 'bunch',
 'bunim',
 'bush',
 'but',
 'but',
 'by',
 'calabasas',
 'california',
 'came',
 'cancer',
 'capture',
 'career',
 'careers',
 'careers',
 'cast',
 'cast',
 'cast',
 'catfights',
 'cattle',
 'caused',
 'ceremony',
 'champion',
 'champion',
 'chaotic',
 'character',
 'cheban',
 'children',
 'children',
 'children',
 'children',
 'circulated',
 'clothing',
 'co',
 'co',
 'collections',
 'couple',
 'criticism',
 'd',
 'd',
 'daughter',
 'daughter',
 'daughters',
 'daughters',
 'day',
 'days',
 'deal',
 'deal',
 'decathlon',
 'deceased',
 'december',
 'defended',
 'despite',
 'developed',
 'development',
 'diagnosed',
 'died',
 'disick',
 'divorce',
 'divorce',
 'divorced',
 'don',
 'drive',
 'driving',
 'dropped',
 'during',
 'during',
 'during',
 'dynamics',
 'dynamics',
 'e',
 'e',
 'e',
 'e',
 'eagles',
 'earlier',
 'early',
 'earns',
 'eight',
 'eight',
 'eight',
 'eighth',
 'embraced',
 'ending',
 'endless',
 'entered',
 'entertain',
 'entertaining',
 'entertainment',
 'entertainment',
 'entitled',
 'esophageal',
 'established',
 'established',
 'estimated',
 'estimated',
 'eventually',
 'exceptional',
 'executive',
 'executive',
 'factor',
 'familiar',
 'family',
 'family',
 'family',
 'family',
 'family',
 'family',
 'family',
 'family',
 'fashion',
 'fashion',
 'fashion',
 'fashion',
 'featured',
 'feb',
 'february',
 'february',
 'felder',
 'felder',
 'filed',
 'filing',
 'film',
 'filthy',
 'finale',
 'first',
 'first',
 'focused',
 'followed',
 'following',
 'following',
 'following',
 'for',
 'for',
 'for',
 'for',
 'for',
 'for',
 'for',
 'for',
 'for',
 'for',
 'for',
 'for',
 'former',
 'fortunate',
 'forward',
 'forward',
 'four',
 'fourth',
 'fragrances',
 'frequently',
 'friend',
 'friends',
 'from',
 'from',
 'from',
 'from',
 'from',
 'from',
 'full',
 'further',
 'gained',
 'gave',
 'george',
 'goldman',
 'h',
 'h',
 'had',
 'had',
 'hamptons',
 'haqq',
 'has',
 'has',
 'has',
 'have',
 'have',
 'have',
 'have',
 'have',
 'he',
 'heart',
 'her',
 'her',
 'her',
 'her',
 'her',
 'herself',
 'high',
 'high',
 'highly',
 'hilarious',
 'hilton',
 'hollywood',
 'hollywood',
 'home',
 'host',
 'houghton',
 'hours',
 'humphries',
 'humphries',
 'humphries',
 'husband',
 'in',
 'in',
 'in',
 'in',
 'in',
 'in',
 'in',
 'in',
 'in',
 'in',
 'in',
 'in',
 'in',
 'in',
 'in',
 'in',
 'in',
 'in',
 'in',
 'in',
 'in',
 'in',
 'in',
 'in',
 'in',
 'in',
 'in',
 'in',
 'in',
 'in',
 'in',
 'including',
 'industry',
 'industry',
 'influence',
 'integrated',
 'into',
 'into',
 'into',
 'involved',
 'involved',
 'involved',
 'is',
 'is',
 'is',
 'is',
 'it',
 'it',
 'it',
 'its',
 'j',
 'j',
 'j',
 'jailed',
 'january',
 'jenner',
 'jenner',
 'jenner',
 'jenner',
 'jenners',
 'jersey',
 'joined',
 'jonathan',
 'june',
 'kanye',
 'kardashian',
 'kardashian',
 'kardashian',
 'kardashian',
 'kardashian',
 'kardashian',
 'kardashian',
 'kardashian',
 'kardashian',
 'kardashians',
 'kardashians',
 'kardashians',
 'keep',
 'keeping',
 'kendall',
 'kendall',
 'kendall',
 'khloé',
 'khloé',
 'khloé',
 'khloé',
 'khloé',
 'khloé',
 'kim',
 'kim',
 'kim',
 'kim',
 'kim',
 'kim',
 'kim',
 'kim',
 'kim',
 'kim',
 'kim',
 'kim',
 'kourtney',
 'kourtney',
 'kourtney',
 'kourtney',
 'kourtney',
 'kourtney',
 'kourtney',
 'kris',
 'kris',
 'kris',
 'kris',
 'kris',
 'kris',
 'kris',
 'kris',
 'kristen',
 'kylie',
 'kylie',
 'kylie',
 'lachey',
 'lakers',
 'lamar',
 'later',
 'later',
 'later',
 'launched',
 'launching',
 'leah',
 'leaked',
 'lengthy',
 'life',
 'lindsay',
 'line',
 'lisa',
 'lohan',
 'los',
 'loves',
 'made',
 'made',
 'main',
 'make',
 'malika',
 'march',
 'marriage',
 'marriage',
 'marriage',
 'married',
 'married',
 'married',
 'married',
 'married',
 'mary',
 'media',
 'media',
 'member',
 'member',
 'members',
 'merely',
 'million',
 'million',
 'million',
 'million',
 'million',
 'modeling',
 'month',
 'most',
 'murders',
 'murray',
 'nba',
 'nets',
 'network',
 'new',
 'new',
 'news',
 'nick',
 'nicole',
 'nicole',
 'nine',
 'north',
 'norwood',
 'norwood',
 'notoriety',
 'notoriety',
 'november',
 'o',
 'october',
 'odom',
 'of',
 'of',
 'of',
 'of',
 'of',
 'of',
 'of',
 'of',
 'of',
 'of',
 'of',
 'of',
 'of',
 'of',
 'of',
 'of',
 'olympic',
 'olympics',
 'on',
 'on',
 'on',
 'on',
 'on',
 'on',
 'on',
 'on',
 'on',
 'on',
 'one',
 'one',
 'one',
 'one',
 'one',
 'opening',
 'original',
 'originally',
 'orleans',
 'outlets',
 'own',
 'ownership',
 'owning',
 'paris',
 'per',
 'personal',
 'personal',
 'personalities',
 'petition',
 'player',
 'popular',
 'power',
 'preeclampsia',
 'pregnant',
 'prematurely',
 'premiere',
 'premiere',
 'premiered',
 'president',
 'producer',
 'profile',
 'programming',
 'programming',
 'progressed',
 'promote',
 'public',
 'publicity',
 'publicized',
 'rapper',
 'rapper',
 'ray',
 'ray',
 'reality',
 'reality',
 'received',
 'recording',
 'recurring',
 'recurring',
 'reggie',
 'related',
 'relationship',
 'relationship',
 'relationship',
 'relationships',
 'released',
 'remove',
 'renewed',
 'renewed',
 'reported',
 'reporter',
 'revolves',
 'rich',
 'richie',
 'right',
 'rights',
 'rob',
 'rob',
 'rob',
 'robert',
 'robert',
 'robert',
 'robert',
 'ronald',
 'running',
 'ryan',
 's',
 's',
 's',
 's',
 's',
 's',
 's',
 's',
 's',
 's',
 's',
 'said',
 'said',
 'saints',
 'sarcasm',
 'scott',
 'seacrest',
 'seacrest',
 'seacrest',
 'season',
 'season',
 'season',
 'season',
 'season',
 'season',
 'season',
 'season',
 'seasons',
 'seasons',
 'seasons',
 'seasons',
 'second',
 'second',
 'second',
 'second',
 'second',
 'series',
 'series',
 'series',
 'series',
 'series',
 'series',
 'series',
 'series',
 'series',
 'series',
 'series',
 'series',
 'served',
 'serving',
 'settled',
 'seven',
 'several',
 'several',
 'sex',
 'sex',
 'she',
 'she',
 'she',
 'she',
 'she',
 'she',
 'she',
 'shopper',
 'show',
 'show',
 'show',
 'show',
 'show',
 'show',
 'show',
 'shows',
 'signed',
 'simple',
 'simpson',
 'simpson',
 'since',
 'since',
 'since',
 'singer',
 'singer',
 'sisters',
 'sock',
 'some',
 'son',
 'sons',
 'split',
 'spotlight',
 'star',
 'starred',
 'still',
 'stunt',
 'stylist',
 'stylist',
 'stylist',
 'subject',
 'subsequent',
 'sued',
 'suffering',
 'suit',
 'summer',
 'superstar',
 'supporting',
 'supports',
 'sure',
 'surmised',
 'take',
 'talked',
 'tape',
 'tape',
 'television',
 'television',
 'television',
 'tenth',
 'that',
 'that',
 'that',
 'that',
 'that',
 'that',
 'that',
 'that',
 'that',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'the',
 'their',
 'their',
 'their',
 'their',
 'them',
 'third',
 'third',
 'third',
 'this',
 'this',
 'three',
 'three',
 'through',
 'throughout',
 'throughout',
 'time',
 'titled',
 'to',
 'to',
 'to',
 'to',
 'to',
 'to',
 'to',
 'to',
 'to',
 'to',
 'to',
 'to',
 'together',
 'together',
 'total',
 'trial',
 'truly',
 'two',
 'under',
 'up',
 'ventured',
 'ventures',
 'version',
 'vice',
 'video',
 'viewers',
 'vivid',
 'vivid',
 'vivid',
 'was',
 'was',
 'was',
 'was',
 'was',
 'was',
 'was',
 'was',
 'was',
 'was',
 'was',
 'we',
 'wedding',
 'week',
 'weeks',
 'were',
 'west',
 'when',
 'which',
 'which',
 'while',
 'while',
 'widely',
 'widespread',
 'widespread',
 'wife',
 'will',
 'with',
 'with',
 'with',
 'with',
 'with',
 'with',
 'with',
 'with',
 'with',
 'work',
 'would',
 'x',
 'year',
 'year',
 'year',
 'years',
 'yet']
In [17]:
len(allwords)
Out[17]:
972

How many distinct types of words ("types") are there?

In [18]:
len(set(allwords))
Out[18]:
459
In [19]:
sorted(set(allwords))
Out[19]:
['1',
 '10',
 '13',
 '14',
 '1944',
 '1949',
 '1955',
 '1976',
 '1978',
 '1979',
 '1980',
 '1984',
 '1987',
 '1991',
 '1994',
 '1995',
 '1997',
 '2003',
 '2004',
 '2006',
 '2007',
 '2008',
 '2010',
 '2011',
 '2012',
 '2013',
 '2015',
 '21',
 '24',
 '4',
 '40',
 '5',
 '65',
 '72',
 '8',
 'a',
 'ability',
 'about',
 'actress',
 'adrienne',
 'after',
 'air',
 'aired',
 'airing',
 'all',
 'alleged',
 'also',
 'always',
 'american',
 'an',
 'and',
 'angeles',
 'announced',
 'announcement',
 'another',
 'approximately',
 'april',
 'are',
 'around',
 'arrested',
 'arthur',
 'artist',
 'as',
 'asking',
 'at',
 'attained',
 'attorney',
 'august',
 'back',
 'backlash',
 'bailon',
 'band',
 'be',
 'became',
 'become',
 'been',
 'began',
 'being',
 'berger',
 'birth',
 'born',
 'bought',
 'boutique',
 'boyfriend',
 'brand',
 'brandon',
 'brandy',
 'brody',
 'brother',
 'brown',
 'bruce',
 'bunch',
 'bunim',
 'bush',
 'but',
 'by',
 'calabasas',
 'california',
 'came',
 'cancer',
 'capture',
 'career',
 'careers',
 'cast',
 'catfights',
 'cattle',
 'caused',
 'ceremony',
 'champion',
 'chaotic',
 'character',
 'cheban',
 'children',
 'circulated',
 'clothing',
 'co',
 'collections',
 'couple',
 'criticism',
 'd',
 'daughter',
 'daughters',
 'day',
 'days',
 'deal',
 'decathlon',
 'deceased',
 'december',
 'defended',
 'despite',
 'developed',
 'development',
 'diagnosed',
 'died',
 'disick',
 'divorce',
 'divorced',
 'don',
 'drive',
 'driving',
 'dropped',
 'during',
 'dynamics',
 'e',
 'eagles',
 'earlier',
 'early',
 'earns',
 'eight',
 'eighth',
 'embraced',
 'ending',
 'endless',
 'entered',
 'entertain',
 'entertaining',
 'entertainment',
 'entitled',
 'esophageal',
 'established',
 'estimated',
 'eventually',
 'exceptional',
 'executive',
 'factor',
 'familiar',
 'family',
 'fashion',
 'featured',
 'feb',
 'february',
 'felder',
 'filed',
 'filing',
 'film',
 'filthy',
 'finale',
 'first',
 'focused',
 'followed',
 'following',
 'for',
 'former',
 'fortunate',
 'forward',
 'four',
 'fourth',
 'fragrances',
 'frequently',
 'friend',
 'friends',
 'from',
 'full',
 'further',
 'gained',
 'gave',
 'george',
 'goldman',
 'h',
 'had',
 'hamptons',
 'haqq',
 'has',
 'have',
 'he',
 'heart',
 'her',
 'herself',
 'high',
 'highly',
 'hilarious',
 'hilton',
 'hollywood',
 'home',
 'host',
 'houghton',
 'hours',
 'humphries',
 'husband',
 'in',
 'including',
 'industry',
 'influence',
 'integrated',
 'into',
 'involved',
 'is',
 'it',
 'its',
 'j',
 'jailed',
 'january',
 'jenner',
 'jenners',
 'jersey',
 'joined',
 'jonathan',
 'june',
 'kanye',
 'kardashian',
 'kardashians',
 'keep',
 'keeping',
 'kendall',
 'khloé',
 'kim',
 'kourtney',
 'kris',
 'kristen',
 'kylie',
 'lachey',
 'lakers',
 'lamar',
 'later',
 'launched',
 'launching',
 'leah',
 'leaked',
 'lengthy',
 'life',
 'lindsay',
 'line',
 'lisa',
 'lohan',
 'los',
 'loves',
 'made',
 'main',
 'make',
 'malika',
 'march',
 'marriage',
 'married',
 'mary',
 'media',
 'member',
 'members',
 'merely',
 'million',
 'modeling',
 'month',
 'most',
 'murders',
 'murray',
 'nba',
 'nets',
 'network',
 'new',
 'news',
 'nick',
 'nicole',
 'nine',
 'north',
 'norwood',
 'notoriety',
 'november',
 'o',
 'october',
 'odom',
 'of',
 'olympic',
 'olympics',
 'on',
 'one',
 'opening',
 'original',
 'originally',
 'orleans',
 'outlets',
 'own',
 'ownership',
 'owning',
 'paris',
 'per',
 'personal',
 'personalities',
 'petition',
 'player',
 'popular',
 'power',
 'preeclampsia',
 'pregnant',
 'prematurely',
 'premiere',
 'premiered',
 'president',
 'producer',
 'profile',
 'programming',
 'progressed',
 'promote',
 'public',
 'publicity',
 'publicized',
 'rapper',
 'ray',
 'reality',
 'received',
 'recording',
 'recurring',
 'reggie',
 'related',
 'relationship',
 'relationships',
 'released',
 'remove',
 'renewed',
 'reported',
 'reporter',
 'revolves',
 'rich',
 'richie',
 'right',
 'rights',
 'rob',
 'robert',
 'ronald',
 'running',
 'ryan',
 's',
 'said',
 'saints',
 'sarcasm',
 'scott',
 'seacrest',
 'season',
 'seasons',
 'second',
 'series',
 'served',
 'serving',
 'settled',
 'seven',
 'several',
 'sex',
 'she',
 'shopper',
 'show',
 'shows',
 'signed',
 'simple',
 'simpson',
 'since',
 'singer',
 'sisters',
 'sock',
 'some',
 'son',
 'sons',
 'split',
 'spotlight',
 'star',
 'starred',
 'still',
 'stunt',
 'stylist',
 'subject',
 'subsequent',
 'sued',
 'suffering',
 'suit',
 'summer',
 'superstar',
 'supporting',
 'supports',
 'sure',
 'surmised',
 'take',
 'talked',
 'tape',
 'television',
 'tenth',
 'that',
 'the',
 'their',
 'them',
 'third',
 'this',
 'three',
 'through',
 'throughout',
 'time',
 'titled',
 'to',
 'together',
 'total',
 'trial',
 'truly',
 'two',
 'under',
 'up',
 'ventured',
 'ventures',
 'version',
 'vice',
 'video',
 'viewers',
 'vivid',
 'was',
 'we',
 'wedding',
 'week',
 'weeks',
 'were',
 'west',
 'when',
 'which',
 'while',
 'widely',
 'widespread',
 'wife',
 'will',
 'with',
 'work',
 'would',
 'x',
 'year',
 'years',
 'yet']

Stemming

We might not want to distinguish between air/aired/airing announce/announcing since they talk abuot the same concept. We can do this through stemming.

In [21]:
from nltk.stem import PorterStemmer
stemmer=PorterStemmer()

def getstems(sent):
    return [stemmer.stem(w.lower()) for w in word_splitter.findall(sent)]

sent_words_lower_stemmed = [getstems(sent) for sent in splitter.split(background_nofoot)]

allstemms=[w for sent in sent_words_lower_stemmed
           for w in sent]

set(allstemms)
Out[21]:
{'1',
 '10',
 '13',
 '14',
 '1944',
 '1949',
 '1955',
 '1976',
 '1978',
 '1979',
 '1980',
 '1984',
 '1987',
 '1991',
 '1994',
 '1995',
 '1997',
 '2003',
 '2004',
 '2006',
 '2007',
 '2008',
 '2010',
 '2011',
 '2012',
 '2013',
 '2015',
 '21',
 '24',
 '4',
 '40',
 '5',
 '65',
 '72',
 '8',
 'a',
 'abil',
 'about',
 'actress',
 'adrienn',
 'after',
 'air',
 'all',
 'alleg',
 'also',
 'alway',
 'american',
 'an',
 'and',
 'angel',
 'announc',
 'anoth',
 'approxim',
 'april',
 'are',
 'around',
 'arrest',
 'arthur',
 'artist',
 'as',
 'ask',
 'at',
 'attain',
 'attorney',
 'august',
 'back',
 'backlash',
 'bailon',
 'band',
 'be',
 'becam',
 'becom',
 'been',
 'began',
 'berger',
 'birth',
 'born',
 'bought',
 'boutiqu',
 'boyfriend',
 'brand',
 'brandi',
 'brandon',
 'brodi',
 'brother',
 'brown',
 'bruce',
 'bunch',
 'bunim',
 'bush',
 'but',
 'by',
 'calabasa',
 'california',
 'came',
 'cancer',
 'captur',
 'career',
 'cast',
 'catfight',
 'cattl',
 'caus',
 'ceremoni',
 'champion',
 'chaotic',
 'charact',
 'cheban',
 'children',
 'circul',
 'cloth',
 'co',
 'collect',
 'coupl',
 'critic',
 'd',
 'daughter',
 'day',
 'deal',
 'decathlon',
 'deceas',
 'decemb',
 'defend',
 'despit',
 'develop',
 'diagnos',
 'die',
 'disick',
 'divorc',
 'don',
 'drive',
 'drop',
 'dure',
 'dynam',
 'e',
 'eagl',
 'earli',
 'earlier',
 'earn',
 'eight',
 'eighth',
 'embrac',
 'end',
 'endless',
 'enter',
 'entertain',
 'entitl',
 'esophag',
 'establish',
 'estim',
 'eventu',
 'except',
 'execut',
 'factor',
 'famili',
 'familiar',
 'fashion',
 'featur',
 'feb',
 'februari',
 'felder',
 'file',
 'film',
 'filthi',
 'final',
 'first',
 'focus',
 'follow',
 'for',
 'former',
 'fortun',
 'forward',
 'four',
 'fourth',
 'fragranc',
 'frequent',
 'friend',
 'from',
 'full',
 'further',
 'gain',
 'gave',
 'georg',
 'goldman',
 'h',
 'ha',
 'had',
 'hampton',
 'haqq',
 'have',
 'he',
 'heart',
 'her',
 'herself',
 'high',
 'highli',
 'hilari',
 'hilton',
 'hollywood',
 'home',
 'host',
 'houghton',
 'hour',
 'humphri',
 'husband',
 'in',
 'includ',
 'industri',
 'influenc',
 'integr',
 'into',
 'involv',
 'is',
 'it',
 'j',
 'jail',
 'januari',
 'jenner',
 'jersey',
 'join',
 'jonathan',
 'june',
 'kany',
 'kardashian',
 'keep',
 'kendal',
 'khloé',
 'kim',
 'kourtney',
 'kri',
 'kristen',
 'kyli',
 'lachey',
 'laker',
 'lamar',
 'later',
 'launch',
 'leah',
 'leak',
 'lengthi',
 'life',
 'lindsay',
 'line',
 'lisa',
 'lo',
 'lohan',
 'love',
 'made',
 'main',
 'make',
 'malika',
 'march',
 'mari',
 'marri',
 'marriag',
 'media',
 'member',
 'mere',
 'million',
 'model',
 'month',
 'most',
 'murder',
 'murray',
 'nba',
 'net',
 'network',
 'new',
 'news',
 'nick',
 'nicol',
 'nine',
 'north',
 'norwood',
 'notorieti',
 'novemb',
 'o',
 'octob',
 'odom',
 'of',
 'olymp',
 'on',
 'one',
 'open',
 'origin',
 'orlean',
 'outlet',
 'own',
 'ownership',
 'pari',
 'per',
 'person',
 'petit',
 'player',
 'popular',
 'power',
 'preeclampsia',
 'pregnant',
 'prematur',
 'premier',
 'presid',
 'produc',
 'profil',
 'program',
 'progress',
 'promot',
 'public',
 'rapper',
 'ray',
 'realiti',
 'receiv',
 'record',
 'recur',
 'reggi',
 'relat',
 'relationship',
 'releas',
 'remov',
 'renew',
 'report',
 'revolv',
 'rich',
 'richi',
 'right',
 'rob',
 'robert',
 'ronald',
 'run',
 'ryan',
 's',
 'said',
 'saint',
 'sarcasm',
 'scott',
 'seacrest',
 'season',
 'second',
 'seri',
 'serv',
 'settl',
 'seven',
 'sever',
 'sex',
 'she',
 'shopper',
 'show',
 'sign',
 'simpl',
 'simpson',
 'sinc',
 'singer',
 'sister',
 'sock',
 'some',
 'son',
 'split',
 'spotlight',
 'star',
 'still',
 'stunt',
 'stylist',
 'su',
 'subject',
 'subsequ',
 'suffer',
 'suit',
 'summer',
 'superstar',
 'support',
 'sure',
 'surmis',
 'take',
 'talk',
 'tape',
 'televis',
 'tenth',
 'that',
 'the',
 'their',
 'them',
 'thi',
 'third',
 'three',
 'through',
 'throughout',
 'time',
 'titl',
 'to',
 'togeth',
 'total',
 'trial',
 'truli',
 'two',
 'under',
 'up',
 'ventur',
 'version',
 'vice',
 'video',
 'viewer',
 'vivid',
 'wa',
 'we',
 'wed',
 'week',
 'were',
 'west',
 'when',
 'which',
 'while',
 'wide',
 'widespread',
 'wife',
 'will',
 'with',
 'work',
 'would',
 'x',
 'year',
 'yet'}

Answering queries on the data

We will try to retrieve the closest matching sentence to a given query. To do this, we must define what "closest" means. In other words, we need a similarity measure.

A simple one is the number of types in common between the query and the sentence.

In [22]:
def types_in_common(query_words, sentence):
    A = set(query_words)
    B = set(sentence)
    return len(A.intersection(B))

A slightly more complex one is the the Jaccard similarity measure, which additionaly takes into account the total number of types that the query and the sentence has.

In [23]:
#later
def jaccard(query_words, sentence):
    A = set(query_words)
    B = set(sentence)
    return float(len(A.intersection(B)))/len(A.union(B))

Next we'll define a basic "search engine" which will go through all the sentences and calculate each one's similarity with the query. It returns a list of sentences sorted by their similarity score (if that score is greater than zero).

To calculate the similarity, this function takes as an argument a similarity_measure function.

In [24]:
def run_search(query, similarity_measure):
    query_words = word_splitter.findall(query)
    query_words = [w.lower() for w in query_words]
    
    sent_scores = [(sent, similarity_measure(query_words, sent))
                   for sent in sent_words_lower]

    sent_scores = sorted(sent_scores, key=itemgetter(1), reverse=True)
    sent_scores = [(sent, score)
                   for sent, score in sent_scores
                   if score > 0]

    joined_sents = [(" ".join(sent), score) for sent, score in sent_scores]
    return joined_sents

Now we'll run two versions of the search engines (one using the types_in_commmon measure and one using the jaccard measure) for two different queries.

In [25]:
run_search("Kourtney",types_in_common)
Out[25]:
[('robert kardashian 1944 2003 and kristen mary kris houghton born 1955 married in 1978 and had four children together daughters kourtney born 1979 kim born 1980 and khloé born 1984 and son rob born 1987',
  1),
 ('khloé kim and kourtney further ventured into fashion opening a high fashion boutique d a s h in calabasas california',
  1),
 ('in 2006 kourtney starred in her first reality television series filthy rich cattle drive',
  1),
 ('on january 4 2015 a tenth season was announced to premiere on feb 8 2015 after the kourtney and khloé take the hamptons season finale',
  1),
 ('the show revolves around the children of kris jenner and originally focused on her children from her first marriage to deceased attorney robert kardashian kourtney kim khloé and rob kourtney s boyfriend scott disick is a main character on the show',
  1),
 ('in the eighth season bruce s sons brandon and brody jenner and brandon s wife leah felder daughter of eagles band member don felder were integrated into the supporting cast while kourtney khloé and kim s friends malika haqq and jonathan cheban joined the series in the second and third seasons',
  1)]
In [26]:
##first add Jaccard
run_search("Kourtney",jaccard)
Out[26]:
[('in 2006 kourtney starred in her first reality television series filthy rich cattle drive',
  0.07692307692307693),
 ('khloé kim and kourtney further ventured into fashion opening a high fashion boutique d a s h in calabasas california',
  0.05555555555555555),
 ('on january 4 2015 a tenth season was announced to premiere on feb 8 2015 after the kourtney and khloé take the hamptons season finale',
  0.047619047619047616),
 ('robert kardashian 1944 2003 and kristen mary kris houghton born 1955 married in 1978 and had four children together daughters kourtney born 1979 kim born 1980 and khloé born 1984 and son rob born 1987',
  0.03571428571428571),
 ('the show revolves around the children of kris jenner and originally focused on her children from her first marriage to deceased attorney robert kardashian kourtney kim khloé and rob kourtney s boyfriend scott disick is a main character on the show',
  0.030303030303030304),
 ('in the eighth season bruce s sons brandon and brody jenner and brandon s wife leah felder daughter of eagles band member don felder were integrated into the supporting cast while kourtney khloé and kim s friends malika haqq and jonathan cheban joined the series in the second and third seasons',
  0.02564102564102564)]

As we will be playing around with the internals of our information retrieval system, let's write a convenience function for displaying the results and highlighting the ones that we know are actually relevant for our information need.

In [27]:
def print_results(orderedlist, relevant_docs=[], maxresults=5):
    """Print search results while highlighting the ones we truly care about"""
    count = 1
    for item, score in orderedlist:
        if item in relevant_docs:
            print("{:d} !!! {:.2f} {}".format(count, score, item))
        elif count <= maxresults:
            print("{:d}     {:.2f} {}".format(count, score, item))
        print()
        count += 1
In [28]:
relevant_docs_champion = ["kris married former olympic champion bruce jenner born 1949 in 1991",
                          "kris second husband 1976 summer olympics decathlon champion bruce jenner is also frequently featured on the show and has been a recurring cast member since the show began"]

The Jaccard measure ranks a completely irrelevant document on #1, gets one right on #2, but the actual best document is all the way down on position 16.

In [29]:
print_results(run_search("the olympic champion in kardashians", jaccard),
              relevant_docs=relevant_docs_champion)
1     0.25 the couple divorced in 1991

2 !!! 0.23 kris married former olympic champion bruce jenner born 1949 in 1991

3     0.15 keeping up with the kardashians premiered on october 14 2007

4     0.14 kendall and kylie have also established careers in the modeling industry

5     0.10 in 2012 she served as a co host during the second season of the american version of the x factor











16 !!! 0.07 kris second husband 1976 summer olympics decathlon champion bruce jenner is also frequently featured on the show and has been a recurring cast member since the show began