DC Python Lab - Class 02/18/2017

This notebook contains the application with real data exercise.

Looking at a recent Atlantic Magazine piece: My president was black

Exercise 1:

From the following header extract:

  1. Extract the title
  2. Extract the introduction
  3. Extract the author
  4. Extract the photographer

Hint: Google something called repr and check what print(repr(header)) tells you.


In [1]:
header = """
    My President Was Black
    A history of the first African American White House—and of what came next

    By Ta-Nehisi Coates
    Photograph by Ian Allen
    """

Let's use the hint

First let's check what repr, how? Try typing ?repr


In [2]:
?repr

In [3]:
print(repr(header))


'\n    My President Was Black\n    A history of the first African American White House—and of what came next\n\n    By Ta-Nehisi Coates\n    Photograph by Ian Allen\n    '

Splitting the header

Now we can see all the elements in our header, we can notice that each part that we need to extract is in between two \n, so let's try to split our header using as reference those \n. You can check the split() method documentation here.


In [4]:
header_list = header.split('\n')

In [5]:
print(header_list)


['', '    My President Was Black', '    A history of the first African American White House—and of what came next', '', '    By Ta-Nehisi Coates', '    Photograph by Ian Allen', '    ']

Let's clean up a little this data.

  1. Remove extra white spaces.
  2. Remove the elements of the list that are empty.

We use the method strip() check the documentation here


In [6]:
#Removing extra white spaces in each element of our list
for i in range(len(header_list)):
    header_list[i] = header_list[i].strip()

In [7]:
print(header_list)


['', 'My President Was Black', 'A history of the first African American White House—and of what came next', '', 'By Ta-Nehisi Coates', 'Photograph by Ian Allen', '']

You can avoid removing the empty spaces, but if you want to remove them then you can follow the next lines.

To remove all the elements that match a condition, we will use filter() and lambda functions.

I used this because I tried to use:

for element in header_list:
    if element == '':
        header_list.remove(element)

but I had troubles, it wasn't deleting all of the ''. Not sure exactly why it happens but you can try this simple example.


In [8]:
##EXAMPLE of remove not doing what I want.

c = ['a', 'a', 'a', 'a', 'a', '', '', '', '']

for element in c:
     if element == '':
        c.remove(element)

print(c)


['a', 'a', 'a', 'a', 'a', '', '']

Comming back and deleting the ''


In [9]:
header_list = list(filter(lambda item: item!='' , header_list))

In [10]:
print(header_list)


['My President Was Black', 'A history of the first African American White House—and of what came next', 'By Ta-Nehisi Coates', 'Photograph by Ian Allen']

Now our data is clean and neat, let's get the things we were assigned to. Refreshing the exercise stament, we need:

  1. Extract the title
  2. Extract the introduction
  3. Extract the author
  4. Extract the photographer

Getting the title and introduction (easy ones)


In [11]:
title = header_list[0]
intro = header_list[1]

Let's print them!


In [12]:
print('The title is: ', title)
print('The intro is: ', intro)


The title is:  My President Was Black
The intro is:  A history of the first African American White House—and of what came next

Another way of formatting print statements is by doing the following. Remeber that \n means "go to the next line".


In [13]:
print('The title is: {}. \nThe introduction is: {}.'.format(title, intro))


The title is: My President Was Black. 
The introduction is: A history of the first African American White House—and of what came next.

Getting the author and the photographer

Notice that for the author we need to strip from the 3rd element in th header_list the string 'By '. In the case of the photographer we need to strip the string 'Photograph by ' from the 4th element.


In [14]:
author = header_list[2].strip('By ')
photographer = header_list[3].strip('Photograph by ')

In [15]:
print('The author is: {}. \nThe photographer is: {}.'.format(author, photographer))


The author is: Ta-Nehisi Coates. 
The photographer is: Ian Allen.

Let's print them all together.

If you don't feel comfortable with the format priting you can always do:


In [16]:
print('Title       : ', title)
print('Introduction: ', intro)
print('Author      : ', author)
print('Photographer: ', photographer)


Title       :  My President Was Black
Introduction:  A history of the first African American White House—and of what came next
Author      :  Ta-Nehisi Coates
Photographer:  Ian Allen

Exercise 2:

Using the first paragraph:

  1. How many words are in the first paragraph?
  2. How many sentences are in the first paragraph?
  3. How many times is the word 'Obama' is in the first paragraph?
  4. If you remove all of the punctuation and lower case all text, how many words?

In [17]:
first_paragraph = """
In the waning days of President Barack Obama’s administration, he and his wife, Michelle, hosted a farewell party, the full import of which no one could then grasp. It was late October, Friday the 21st, and the president had spent many of the previous weeks, as he would spend the two subsequent weeks, campaigning for the Democratic presidential nominee, Hillary Clinton. Things were looking up. Polls in the crucial states of Virginia and Pennsylvania showed Clinton with solid advantages. The formidable GOP strongholds of Georgia and Texas were said to be under threat. The moment seemed to buoy Obama. He had been light on his feet in these last few weeks, cracking jokes at the expense of Republican opponents and laughing off hecklers. At a rally in Orlando on October 28, he greeted a student who would be introducing him by dancing toward her and then noting that the song playing over the loudspeakers—the Gap Band’s “Outstanding”—was older than she was. “This is classic!” he said. Then he flashed the smile that had launched America’s first black presidency, and started dancing again. Three months still remained before Inauguration Day, but staffers had already begun to count down the days. They did this with a mix of pride and longing—like college seniors in early May. They had no sense of the world they were graduating into. None of us did.
"""

In [18]:
repr(first_paragraph)


Out[18]:
"'\\nIn the waning days of President Barack Obama’s administration, he and his wife, Michelle, hosted a farewell party, the full import of which no one could then grasp. It was late October, Friday the 21st, and the president had spent many of the previous weeks, as he would spend the two subsequent weeks, campaigning for the Democratic presidential nominee, Hillary Clinton. Things were looking up. Polls in the crucial states of Virginia and Pennsylvania showed Clinton with solid advantages. The formidable GOP strongholds of Georgia and Texas were said to be under threat. The moment seemed to buoy Obama. He had been light on his feet in these last few weeks, cracking jokes at the expense of Republican opponents and laughing off hecklers. At a rally in Orlando on October 28, he greeted a student who would be introducing him by dancing toward her and then noting that the song playing over the loudspeakers—the Gap Band’s “Outstanding”—was older than she was. “This is classic!” he said. Then he flashed the smile that had launched America’s first black presidency, and started dancing again. Three months still remained before Inauguration Day, but staffers had already begun to count down the days. They did this with a mix of pride and longing—like college seniors in early May. They had no sense of the world they were graduating into. None of us did.\\n'"

How many words are in the first paragraph?

To answer answer this question let's first split our paragraph and save the result in a list. We will have plenty of elements that are not words but we will remove them from our list if we need it.


In [19]:
paragraph_list = first_paragraph.split()

Let's take a look at the split paragraph.


In [20]:
print(paragraph_list)


['In', 'the', 'waning', 'days', 'of', 'President', 'Barack', 'Obama’s', 'administration,', 'he', 'and', 'his', 'wife,', 'Michelle,', 'hosted', 'a', 'farewell', 'party,', 'the', 'full', 'import', 'of', 'which', 'no', 'one', 'could', 'then', 'grasp.', 'It', 'was', 'late', 'October,', 'Friday', 'the', '21st,', 'and', 'the', 'president', 'had', 'spent', 'many', 'of', 'the', 'previous', 'weeks,', 'as', 'he', 'would', 'spend', 'the', 'two', 'subsequent', 'weeks,', 'campaigning', 'for', 'the', 'Democratic', 'presidential', 'nominee,', 'Hillary', 'Clinton.', 'Things', 'were', 'looking', 'up.', 'Polls', 'in', 'the', 'crucial', 'states', 'of', 'Virginia', 'and', 'Pennsylvania', 'showed', 'Clinton', 'with', 'solid', 'advantages.', 'The', 'formidable', 'GOP', 'strongholds', 'of', 'Georgia', 'and', 'Texas', 'were', 'said', 'to', 'be', 'under', 'threat.', 'The', 'moment', 'seemed', 'to', 'buoy', 'Obama.', 'He', 'had', 'been', 'light', 'on', 'his', 'feet', 'in', 'these', 'last', 'few', 'weeks,', 'cracking', 'jokes', 'at', 'the', 'expense', 'of', 'Republican', 'opponents', 'and', 'laughing', 'off', 'hecklers.', 'At', 'a', 'rally', 'in', 'Orlando', 'on', 'October', '28,', 'he', 'greeted', 'a', 'student', 'who', 'would', 'be', 'introducing', 'him', 'by', 'dancing', 'toward', 'her', 'and', 'then', 'noting', 'that', 'the', 'song', 'playing', 'over', 'the', 'loudspeakers—the', 'Gap', 'Band’s', '“Outstanding”—was', 'older', 'than', 'she', 'was.', '“This', 'is', 'classic!”', 'he', 'said.', 'Then', 'he', 'flashed', 'the', 'smile', 'that', 'had', 'launched', 'America’s', 'first', 'black', 'presidency,', 'and', 'started', 'dancing', 'again.', 'Three', 'months', 'still', 'remained', 'before', 'Inauguration', 'Day,', 'but', 'staffers', 'had', 'already', 'begun', 'to', 'count', 'down', 'the', 'days.', 'They', 'did', 'this', 'with', 'a', 'mix', 'of', 'pride', 'and', 'longing—like', 'college', 'seniors', 'in', 'early', 'May.', 'They', 'had', 'no', 'sense', 'of', 'the', 'world', 'they', 'were', 'graduating', 'into.', 'None', 'of', 'us', 'did.']

As you can notice, the punctuation doesn't the word count because the symbols are attached to the previous word. However, the em dash '—' symbol links two words and that will affect the count, so let's replace them with a space so when we split by spaces it will do what we want. If you don't have the em dash symbol in your keyword you can generate it by doing (Ctrl+Shift+u)+2014.


In [21]:
#We want to keep first_paragraph without changes, so we create a copy and work with that.
revised_paragraph = first_paragraph

In [22]:
for element in revised_paragraph:
    if element == '—':
        revised_paragraph = revised_paragraph.replace(element, ' ')

In [23]:
print(revised_paragraph)


In the waning days of President Barack Obama’s administration, he and his wife, Michelle, hosted a farewell party, the full import of which no one could then grasp. It was late October, Friday the 21st, and the president had spent many of the previous weeks, as he would spend the two subsequent weeks, campaigning for the Democratic presidential nominee, Hillary Clinton. Things were looking up. Polls in the crucial states of Virginia and Pennsylvania showed Clinton with solid advantages. The formidable GOP strongholds of Georgia and Texas were said to be under threat. The moment seemed to buoy Obama. He had been light on his feet in these last few weeks, cracking jokes at the expense of Republican opponents and laughing off hecklers. At a rally in Orlando on October 28, he greeted a student who would be introducing him by dancing toward her and then noting that the song playing over the loudspeakers the Gap Band’s “Outstanding” was older than she was. “This is classic!” he said. Then he flashed the smile that had launched America’s first black presidency, and started dancing again. Three months still remained before Inauguration Day, but staffers had already begun to count down the days. They did this with a mix of pride and longing like college seniors in early May. They had no sense of the world they were graduating into. None of us did.

Now our revised_paragraph is the same than the first paragraph but without the "em dashes" . Let's split it and then count the words.


In [24]:
words_list = revised_paragraph.split()

To count the words we just need to know the length of our list. To do that we use len()


In [25]:
words = len(words_list)

In [26]:
print('The amount of words in first_paragraph is: ', words)


The amount of words in first_paragraph is:  232

How many sentences are in the first paragraph?

To find the number of sentences we just need to split the initial paragraph by using the delimiter '.', but what happens when we have a '?' ? If there is one we should take that into account. We can replace them by '.' just for the counting, and after that we are good to go.


In [27]:
#We want to keep first_paragraph without changes, so we create a copy, in this case replacing ? by .
#and work with that copy.
sentence_paragraph = first_paragraph.replace('?', '.')
sentence_paragraph = sentence_paragraph.replace('\n', '')

In [28]:
#Split the paragraph into sentences
sentence_list = sentence_paragraph.split('.')

In [29]:
print(sentence_list)


['In the waning days of President Barack Obama’s administration, he and his wife, Michelle, hosted a farewell party, the full import of which no one could then grasp', ' It was late October, Friday the 21st, and the president had spent many of the previous weeks, as he would spend the two subsequent weeks, campaigning for the Democratic presidential nominee, Hillary Clinton', ' Things were looking up', ' Polls in the crucial states of Virginia and Pennsylvania showed Clinton with solid advantages', ' The formidable GOP strongholds of Georgia and Texas were said to be under threat', ' The moment seemed to buoy Obama', ' He had been light on his feet in these last few weeks, cracking jokes at the expense of Republican opponents and laughing off hecklers', ' At a rally in Orlando on October 28, he greeted a student who would be introducing him by dancing toward her and then noting that the song playing over the loudspeakers—the Gap Band’s “Outstanding”—was older than she was', ' “This is classic!” he said', ' Then he flashed the smile that had launched America’s first black presidency, and started dancing again', ' Three months still remained before Inauguration Day, but staffers had already begun to count down the days', ' They did this with a mix of pride and longing—like college seniors in early May', ' They had no sense of the world they were graduating into', ' None of us did', '']

In [30]:
#Let's remove the '' elements
sentence_list = list(filter(lambda item: item!='' , sentence_list))

In [31]:
print(sentence_list)


['In the waning days of President Barack Obama’s administration, he and his wife, Michelle, hosted a farewell party, the full import of which no one could then grasp', ' It was late October, Friday the 21st, and the president had spent many of the previous weeks, as he would spend the two subsequent weeks, campaigning for the Democratic presidential nominee, Hillary Clinton', ' Things were looking up', ' Polls in the crucial states of Virginia and Pennsylvania showed Clinton with solid advantages', ' The formidable GOP strongholds of Georgia and Texas were said to be under threat', ' The moment seemed to buoy Obama', ' He had been light on his feet in these last few weeks, cracking jokes at the expense of Republican opponents and laughing off hecklers', ' At a rally in Orlando on October 28, he greeted a student who would be introducing him by dancing toward her and then noting that the song playing over the loudspeakers—the Gap Band’s “Outstanding”—was older than she was', ' “This is classic!” he said', ' Then he flashed the smile that had launched America’s first black presidency, and started dancing again', ' Three months still remained before Inauguration Day, but staffers had already begun to count down the days', ' They did this with a mix of pride and longing—like college seniors in early May', ' They had no sense of the world they were graduating into', ' None of us did']

Now our sentences_list just contains the sentences, let's use len() to count the amount of sentences.


In [32]:
sentences = len(sentence_list)

In [33]:
print('The amount of sentences in first_paragraph is: ', sentences)


The amount of sentences in first_paragraph is:  14

How many times is the word 'Obama' is in the first paragraph?

If you read the paragraph you might have notice that in some parts the Word Obama appears as "Obama's". We want to count that case; therefore, we will look for the string 'Obama' in wach word of the word_list. If the string is in the word we will add 1 to the variable obama_count (initialized in 0).


In [34]:
obama_count = 0
for word in words_list:
    if 'Obama' in word:
        obama_count +=1

In [35]:
print(obama_count)


2

In [36]:
print('The word Obama in first_paragraph appears {} times.'.format(obama_count))


The word Obama in first_paragraph appears 2 times.

If you remove all of the punctuation and lower case all text, how many words?

This sounds like a tricky question. Why lower case would affect word counting? In the answer of part one we were asked to count the words and we did it. Lower case the whole text and removing punctuation won't affect that count. However, removing all type of punctuation might affect. For example, think in the cases where we have words like "Obama's" in this case the initial word-count counts that case as 1, even though we know that "Obama's" = "Obama is" which are 2 words.

So, let's remove punctuation and count again.

Lower case the first_paragraph.

We can do this in one line, because strings have a method called lower() that will do that for us.


In [37]:
#Lower case the whole paragraph
lower_paragraph = first_paragraph.lower()

In [38]:
print(lower_paragraph)


in the waning days of president barack obama’s administration, he and his wife, michelle, hosted a farewell party, the full import of which no one could then grasp. it was late october, friday the 21st, and the president had spent many of the previous weeks, as he would spend the two subsequent weeks, campaigning for the democratic presidential nominee, hillary clinton. things were looking up. polls in the crucial states of virginia and pennsylvania showed clinton with solid advantages. the formidable gop strongholds of georgia and texas were said to be under threat. the moment seemed to buoy obama. he had been light on his feet in these last few weeks, cracking jokes at the expense of republican opponents and laughing off hecklers. at a rally in orlando on october 28, he greeted a student who would be introducing him by dancing toward her and then noting that the song playing over the loudspeakers—the gap band’s “outstanding”—was older than she was. “this is classic!” he said. then he flashed the smile that had launched america’s first black presidency, and started dancing again. three months still remained before inauguration day, but staffers had already begun to count down the days. they did this with a mix of pride and longing—like college seniors in early may. they had no sense of the world they were graduating into. none of us did.

Remove punctuation.

To approach this exercise we will use some of the string constants available in python. Thanksfully, there is one that has all the punctuation (string.punctuation). Once we have this string, we will do a for loop on the elements of that constant and every time we find one of those elements in our paragraph, we will replace it for a space (' ').

Since


In [39]:
#First we import the string constants available in python.  
import string

In [40]:
#Let's print the string punctuation.
print(string.punctuation)


!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

In [41]:
#loop in the character of string.punctuation and we replace the characters that appear
#in our lower_paragraph for a space. 
for character in string.punctuation:
    lower_paragraph = lower_paragraph.replace(character, ' ')

In [42]:
print(lower_paragraph)


in the waning days of president barack obama’s administration  he and his wife  michelle  hosted a farewell party  the full import of which no one could then grasp  it was late october  friday the 21st  and the president had spent many of the previous weeks  as he would spend the two subsequent weeks  campaigning for the democratic presidential nominee  hillary clinton  things were looking up  polls in the crucial states of virginia and pennsylvania showed clinton with solid advantages  the formidable gop strongholds of georgia and texas were said to be under threat  the moment seemed to buoy obama  he had been light on his feet in these last few weeks  cracking jokes at the expense of republican opponents and laughing off hecklers  at a rally in orlando on october 28  he greeted a student who would be introducing him by dancing toward her and then noting that the song playing over the loudspeakers—the gap band’s “outstanding”—was older than she was  “this is classic ” he said  then he flashed the smile that had launched america’s first black presidency  and started dancing again  three months still remained before inauguration day  but staffers had already begun to count down the days  they did this with a mix of pride and longing—like college seniors in early may  they had no sense of the world they were graduating into  none of us did 

It seems that our paragraph is not using the curly quation marks, single and double. Those are not in our strin.punctuation constant and the "em dash" either. Let's create another constant string with all the ramining characters we want to remove and take them out. We might want to add also the '\n' symbol.

Probably you don't have non straight quotation marks, but you can creat them using unicode:

  • ‘: (Ctrl+Shift+u)+2018
  • ’: (Ctrl+Shift+u)+2019
  • “: (Ctrl+Shift+u)+201c
  • ”: (Ctrl+Shift+u)+201d
  • —: (Ctrl+Shift+u)+2014

In [43]:
more_punct = '’‘“”—\n'

In [44]:
for character in more_punct:
    lower_paragraph = lower_paragraph.replace(character, ' ')

In [45]:
print(lower_paragraph)


 in the waning days of president barack obama s administration  he and his wife  michelle  hosted a farewell party  the full import of which no one could then grasp  it was late october  friday the 21st  and the president had spent many of the previous weeks  as he would spend the two subsequent weeks  campaigning for the democratic presidential nominee  hillary clinton  things were looking up  polls in the crucial states of virginia and pennsylvania showed clinton with solid advantages  the formidable gop strongholds of georgia and texas were said to be under threat  the moment seemed to buoy obama  he had been light on his feet in these last few weeks  cracking jokes at the expense of republican opponents and laughing off hecklers  at a rally in orlando on october 28  he greeted a student who would be introducing him by dancing toward her and then noting that the song playing over the loudspeakers the gap band s  outstanding  was older than she was   this is classic   he said  then he flashed the smile that had launched america s first black presidency  and started dancing again  three months still remained before inauguration day  but staffers had already begun to count down the days  they did this with a mix of pride and longing like college seniors in early may  they had no sense of the world they were graduating into  none of us did  

Now we removed all kind of punctuation, let's create our list and count the elements to know the amount of words.


In [46]:
no_punctuation_list = lower_paragraph.split()
words_no_punctuation = len(no_punctuation_list)

In [47]:
print('The amount of words in the paragraph with no punctuation is: ', words_no_punctuation)


The amount of words in the paragraph with no punctuation is:  235

Printing all together:


In [48]:
print('The amount of words in first_paragraph is: ', words)
print('The amount of sentences in first_paragraph is: ', sentences)
print('The word Obama in first_paragraph appears {} times.'.format(obama_count))
print('The amount of words in the paragraph with no punctuation is: ', words_no_punctuation)


The amount of words in first_paragraph is:  232
The amount of sentences in first_paragraph is:  14
The word Obama in first_paragraph appears 2 times.
The amount of words in the paragraph with no punctuation is:  235

Eercise 3: Advanced

  1. Open the article_part_one.txt with python.
  2. How many words are in part one?
  3. How many sentences are in part one?
  4. Which words follow 'black' and 'white' in the text? Which ones are used the most for each?

Hint: Google open file with python

Open file with python.

Sicne this is the advance exercise we will try to use cool stuffs so we learn more. Because, you might have changed the name of the file when you copy it to your working folder. Or maybe the location where is it it's not the same than mine, and we want to have that freedom we will use the input() function to especify the path (location) of the file we want to open

For example, in my case it will be data/article_part_one.txt


In [49]:
name = input('Enter file name with its path location: ')


Enter file name with its path location: data/article_part_one.txt

In [50]:
with open(name, 'r') as file:
    article = file.read()

In [51]:
print(article)


My President Was Black
A history of the first African American White House—and of what came next

By Ta-Nehisi Coates
Photograph by Ian Allen

“They’re a rotten crowd,” I shouted across the lawn. “You’re worth the whole damn bunch put together.”

— F. Scott Fitzgerald, The Great Gatsby

I. “LOVE WILL MAKE YOU DO WRONG”

In the waning days of President Barack Obama’s administration, he and his wife, Michelle, hosted a farewell party, the full import of which no one could then grasp. It was late October, Friday the 21st, and the president had spent many of the previous weeks, as he would spend the two subsequent weeks, campaigning for the Democratic presidential nominee, Hillary Clinton. Things were looking up. Polls in the crucial states of Virginia and Pennsylvania showed Clinton with solid advantages. The formidable GOP strongholds of Georgia and Texas were said to be under threat. The moment seemed to buoy Obama. He had been light on his feet in these last few weeks, cracking jokes at the expense of Republican opponents and laughing off hecklers. At a rally in Orlando on October 28, he greeted a student who would be introducing him by dancing toward her and then noting that the song playing over the loudspeakers—the Gap Band’s “Outstanding”—was older than she was. “This is classic!” he said. Then he flashed the smile that had launched America’s first black presidency, and started dancing again. Three months still remained before Inauguration Day, but staffers had already begun to count down the days. They did this with a mix of pride and longing—like college seniors in early May. They had no sense of the world they were graduating into. None of us did.

The farewell party, presented by BET (Black Entertainment Television), was the last in a series of concerts the first couple had hosted at the White House. Guests were asked to arrive at 5:30 p.m. By 6, two long lines stretched behind the Treasury Building, where the Secret Service was checking names. The people in these lines were, in the main, black, and their humor reflected it. The brisker queue was dubbed the “good-hair line” by one guest, and there was laughter at the prospect of the Secret Service subjecting us all to a “brown-paper-bag test.” This did not come to pass, but security was tight. Several guests were told to stand in a makeshift pen and wait to have their backgrounds checked a second time.

Dave Chappelle was there. He coolly explained the peril and promise of comedy in what was then still only a remotely potential Donald Trump presidency: “I mean, we never had a guy have his own pussygate scandal.” Everyone laughed. A few weeks later, he would be roundly criticized for telling a crowd at the Cutting Room, in New York, that he had voted for Clinton but did not feel good about it. “She’s going to be on a coin someday,” Chappelle said. “And her behavior has not been coinworthy.” But on this crisp October night, everything felt inevitable and grand. There was a slight wind. It had been in the 80s for much of that week. Now, as the sun set, the season remembered its name. Women shivered in their cocktail dresses. Gentlemen chivalrously handed over their suit coats. But when Naomi Campbell strolled past the security pen in a sleeveless number, she seemed as invulnerable as ever.

Cellphones were confiscated to prevent surreptitious recordings from leaking out. (This effort was unsuccessful. The next day, a partygoer would tweet a video of the leader of the free world dancing to Drake’s “Hotline Bling.”) After withstanding the barrage of security, guests were welcomed into the East Wing of the White House, and then ushered back out into the night, where they boarded a succession of orange-and-green trolleys. The singer and actress Janelle Monáe, her famous and fantastic pompadour preceding her, stepped on board and joked with a companion about the historical import of “sitting in the back of the bus.” She took a seat three rows from the front and hummed into the night. The trolley dropped the guests on the South Lawn, in front of a giant tent. The South Lawn’s fountain was lit up with blue lights. The White House proper loomed like a ghost in the distance. I heard the band, inside, beginning to play Al Green’s “Let’s Stay Together.”

“Well, you can tell what type of night this is,” Obama said from the stage, opening the event. “Not the usual ruffles and flourishes!”

The crowd roared.

“This must be a BET event!”

The crowd roared louder still.

Obama placed the concert in the White House’s musical tradition, noting that guests of the Kennedys had once done the twist at the residence—“the twerking of their time,” he said, before adding, “There will be no twerking tonight. At least not by me.”

The Obamas are fervent and eclectic music fans. In the past eight years, they have hosted performances at the White House by everyone from Mavis Staples to Bob Dylan to Tony Bennett to the Blind Boys of Alabama. After the rapper Common was invited to perform in 2011, a small fracas ensued in the right-wing media. He performed anyway—and was invited back again this glorious fall evening and almost stole the show. The crowd sang along to the hook for his hit ballad “The Light.” And when he brought on the gospel singer Yolanda Adams to fill in for John Legend on the Oscar-winning song “Glory,” glee turned to rapture.

De La Soul was there. The hip-hop trio had come of age as boyish B-boys with Gumby-style high-top fades. Now they moved across the stage with a lovely mix of lethargy and grace, like your favorite uncle making his way down the Soul Train line, wary of throwing out a hip. I felt a sense of victory watching them rock the crowd, all while keeping it in the pocket. The victory belonged to hip-hop—an art form birthed in the burning Bronx and now standing full grown, at the White House, unbroken and unedited. Usher led the crowd in a call-and-response: “Say it loud, I’m black and I’m proud.” Jill Scott showed off her operatic chops. Bell Biv DeVoe, contemporaries of De La, made history with their performance by surely becoming the first group to suggest to a presidential audience that one should “never trust a big butt and a smile.”

The ties between the Obama White House and the hip-hop community are genuine. The Obamas are social with Beyoncé and Jay-Z. They hosted Chance the Rapper and Frank Ocean at a state dinner, and last year invited Swizz Beatz, Busta Rhymes, and Ludacris, among others, to discuss criminal-justice reform and other initiatives. Obama once stood in the Rose Garden passing large flash cards to the Hamilton creator and rapper Lin-Manuel Miranda, who then freestyled using each word on the cards. “Drop the beat,” Obama said, inaugurating the session. At 55, Obama is younger than pioneering hip-hop artists like Afrika Bambaataa, DJ Kool Herc, and Kurtis Blow. If Obama’s enormous symbolic power draws primarily from being the country’s first black president, it also draws from his membership in hip-hop’s foundational generation.

That night, the men were sharp in their gray or black suits and optional ties. Those who were not in suits had chosen to make a statement, like the dark-skinned young man who strolled in, sockless, with blue jeans cuffed so as to accentuate his gorgeous black-suede loafers. Everything in his ensemble seemed to say, “My fellow Americans, do not try this at home.” There were women in fur jackets and high heels; others with sculpted naturals, the sides shaved close, the tops blooming into curls; others still in gold bamboo earrings and long blond dreads. When the actor Jesse Williams took the stage, seemingly awed before such black excellence, before such black opulence, assembled just feet from where slaves had once toiled, he simply said, “Look where we are. Look where we are right now.”

This would not happen again, and everyone knew it. It was not just that there might never be another African American president of the United States. It was the feeling that this particular black family, the Obamas, represented the best of black people, the ultimate credit to the race, incomparable in elegance and bearing. “There are no more,” the comedian Sinbad joked back in 2010. “There are no black men raised in Kansas and Hawaii. That’s the last one. Y’all better treat this one right. The next one gonna be from Cleveland. He gonna wear a perm. Then you gonna see what it’s really like.” Throughout their residency, the Obamas had refrained from showing America “what it’s really like,” and had instead followed the first lady’s motto, “When they go low, we go high.” This was the ideal—black and graceful under fire—saluted that evening. The president was lionized as “our crown jewel.” The first lady was praised as the woman “who put the O in Obama.”

Barack Obama’s victories in 2008 and 2012 were dismissed by some of his critics as merely symbolic for African Americans. But there is nothing “mere” about symbols. The power embedded in the word nigger is also symbolic. Burning crosses do not literally raise the black poverty rate, and the Confederate flag does not directly expand the wealth gap.

Much as the unbroken ranks of 43 white male presidents communicated that the highest office of government in the country—indeed, the most powerful political offices in the world—was off-limits to black individuals, the election of Barack Obama communicated that the prohibition had been lifted. It communicated much more. Before Obama triumphed in 2008, the most-famous depictions of black success tended to be entertainers or athletes. But Obama had shown that it was “possible to be smart and cool at the same damn time,” as Jesse Williams put it at the BET party. Moreover, he had not embarrassed his people with a string of scandals. Against the specter of black pathology, against the narrow images of welfare moms and deadbeat dads, his time in the White House had been an eight-year showcase of a healthy and successful black family spanning three generations, with two dogs to boot. In short, he became a symbol of black people’s everyday, extraordinary Americanness.

Whiteness in America is a different symbol—a badge of advantage. In a country of professed meritocratic competition, this badge has long ensured an unerring privilege, represented in a 220-year monopoly on the highest office in the land. For some not-insubstantial sector of the country, the elevation of Barack Obama communicated that the power of the badge had diminished. For eight long years, the badge-holders watched him. They saw footage of the president throwing bounce passes and shooting jumpers. They saw him enter a locker room, give a businesslike handshake to a white staffer, and then greet Kevin Durant with something more soulful. They saw his wife dancing with Jimmy Fallon and posing, resplendent, on the covers of magazines that had, only a decade earlier, been almost exclusively, if unofficially, reserved for ladies imbued with the great power of the badge.

For the preservation of the badge, insidious rumors were concocted to denigrate the first black White House. Obama gave free cellphones to disheveled welfare recipients. Obama went to Europe and complained that “ordinary men and women are too small-minded to govern their own affairs.” Obama had inscribed an Arabic saying on his wedding ring, then stopped wearing the ring, in observance of Ramadan. He canceled the National Day of Prayer; refused to sign certificates for Eagle Scouts; faked his attendance at Columbia University; and used a teleprompter to address a group of elementary-school students. The badge-holders fumed. They wanted their country back. And, though no one at the farewell party knew it, in a couple of weeks they would have it.

On this October night, though, the stage belonged to another America. At the end of the party, Obama looked out into the crowd, searching for Dave Chappelle. “Where’s Dave?” he cried. And then, finding him, the president referenced Chappelle’s legendary Brooklyn concert. “You got your block party. I got my block party.” Then the band struck up Al Green’s “Love and Happiness”—the evening’s theme. The president danced in a line next to Ronnie DeVoe. Together they mouthed the lyrics: “Make you do right. Love will make you do wrong.”

How many words are in part one?

Let's remove all the punctuation we can and we will have just words to count.


In [52]:
#Let's create a string with all the punctuation we want to remove to count words.
all_punct = string.punctuation + more_punct

In [53]:
all_punct


Out[53]:
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~’‘“”—\n'

Now we replace all the punctuation characters for a space. We create an article to modify that is a copy of the original article.


In [54]:
#We will modify article_no_punct but we want to keep intact article. So
article_no_punct = article

In [55]:
for char in all_punct:
    if char in article_no_punct:
        article_no_punct = article_no_punct.replace(char, ' ')

In [56]:
article_no_punct


Out[56]:
'My President Was Black A history of the first African American White House and of what came next  By Ta Nehisi Coates Photograph by Ian Allen   They re a rotten crowd   I shouted across the lawn   You re worth the whole damn bunch put together      F  Scott Fitzgerald  The Great Gatsby  I   LOVE WILL MAKE YOU DO WRONG   In the waning days of President Barack Obama s administration  he and his wife  Michelle  hosted a farewell party  the full import of which no one could then grasp  It was late October  Friday the 21st  and the president had spent many of the previous weeks  as he would spend the two subsequent weeks  campaigning for the Democratic presidential nominee  Hillary Clinton  Things were looking up  Polls in the crucial states of Virginia and Pennsylvania showed Clinton with solid advantages  The formidable GOP strongholds of Georgia and Texas were said to be under threat  The moment seemed to buoy Obama  He had been light on his feet in these last few weeks  cracking jokes at the expense of Republican opponents and laughing off hecklers  At a rally in Orlando on October 28  he greeted a student who would be introducing him by dancing toward her and then noting that the song playing over the loudspeakers the Gap Band s  Outstanding  was older than she was   This is classic   he said  Then he flashed the smile that had launched America s first black presidency  and started dancing again  Three months still remained before Inauguration Day  but staffers had already begun to count down the days  They did this with a mix of pride and longing like college seniors in early May  They had no sense of the world they were graduating into  None of us did   The farewell party  presented by BET  Black Entertainment Television   was the last in a series of concerts the first couple had hosted at the White House  Guests were asked to arrive at 5 30 p m  By 6  two long lines stretched behind the Treasury Building  where the Secret Service was checking names  The people in these lines were  in the main  black  and their humor reflected it  The brisker queue was dubbed the  good hair line  by one guest  and there was laughter at the prospect of the Secret Service subjecting us all to a  brown paper bag test   This did not come to pass  but security was tight  Several guests were told to stand in a makeshift pen and wait to have their backgrounds checked a second time   Dave Chappelle was there  He coolly explained the peril and promise of comedy in what was then still only a remotely potential Donald Trump presidency   I mean  we never had a guy have his own pussygate scandal   Everyone laughed  A few weeks later  he would be roundly criticized for telling a crowd at the Cutting Room  in New York  that he had voted for Clinton but did not feel good about it   She s going to be on a coin someday   Chappelle said   And her behavior has not been coinworthy   But on this crisp October night  everything felt inevitable and grand  There was a slight wind  It had been in the 80s for much of that week  Now  as the sun set  the season remembered its name  Women shivered in their cocktail dresses  Gentlemen chivalrously handed over their suit coats  But when Naomi Campbell strolled past the security pen in a sleeveless number  she seemed as invulnerable as ever   Cellphones were confiscated to prevent surreptitious recordings from leaking out   This effort was unsuccessful  The next day  a partygoer would tweet a video of the leader of the free world dancing to Drake s  Hotline Bling    After withstanding the barrage of security  guests were welcomed into the East Wing of the White House  and then ushered back out into the night  where they boarded a succession of orange and green trolleys  The singer and actress Janelle Monáe  her famous and fantastic pompadour preceding her  stepped on board and joked with a companion about the historical import of  sitting in the back of the bus   She took a seat three rows from the front and hummed into the night  The trolley dropped the guests on the South Lawn  in front of a giant tent  The South Lawn s fountain was lit up with blue lights  The White House proper loomed like a ghost in the distance  I heard the band  inside  beginning to play Al Green s  Let s Stay Together     Well  you can tell what type of night this is   Obama said from the stage  opening the event   Not the usual ruffles and flourishes    The crowd roared    This must be a BET event    The crowd roared louder still   Obama placed the concert in the White House s musical tradition  noting that guests of the Kennedys had once done the twist at the residence  the twerking of their time   he said  before adding   There will be no twerking tonight  At least not by me    The Obamas are fervent and eclectic music fans  In the past eight years  they have hosted performances at the White House by everyone from Mavis Staples to Bob Dylan to Tony Bennett to the Blind Boys of Alabama  After the rapper Common was invited to perform in 2011  a small fracas ensued in the right wing media  He performed anyway and was invited back again this glorious fall evening and almost stole the show  The crowd sang along to the hook for his hit ballad  The Light   And when he brought on the gospel singer Yolanda Adams to fill in for John Legend on the Oscar winning song  Glory   glee turned to rapture   De La Soul was there  The hip hop trio had come of age as boyish B boys with Gumby style high top fades  Now they moved across the stage with a lovely mix of lethargy and grace  like your favorite uncle making his way down the Soul Train line  wary of throwing out a hip  I felt a sense of victory watching them rock the crowd  all while keeping it in the pocket  The victory belonged to hip hop an art form birthed in the burning Bronx and now standing full grown  at the White House  unbroken and unedited  Usher led the crowd in a call and response   Say it loud  I m black and I m proud   Jill Scott showed off her operatic chops  Bell Biv DeVoe  contemporaries of De La  made history with their performance by surely becoming the first group to suggest to a presidential audience that one should  never trust a big butt and a smile    The ties between the Obama White House and the hip hop community are genuine  The Obamas are social with Beyoncé and Jay Z  They hosted Chance the Rapper and Frank Ocean at a state dinner  and last year invited Swizz Beatz  Busta Rhymes  and Ludacris  among others  to discuss criminal justice reform and other initiatives  Obama once stood in the Rose Garden passing large flash cards to the Hamilton creator and rapper Lin Manuel Miranda  who then freestyled using each word on the cards   Drop the beat   Obama said  inaugurating the session  At 55  Obama is younger than pioneering hip hop artists like Afrika Bambaataa  DJ Kool Herc  and Kurtis Blow  If Obama s enormous symbolic power draws primarily from being the country s first black president  it also draws from his membership in hip hop s foundational generation   That night  the men were sharp in their gray or black suits and optional ties  Those who were not in suits had chosen to make a statement  like the dark skinned young man who strolled in  sockless  with blue jeans cuffed so as to accentuate his gorgeous black suede loafers  Everything in his ensemble seemed to say   My fellow Americans  do not try this at home   There were women in fur jackets and high heels  others with sculpted naturals  the sides shaved close  the tops blooming into curls  others still in gold bamboo earrings and long blond dreads  When the actor Jesse Williams took the stage  seemingly awed before such black excellence  before such black opulence  assembled just feet from where slaves had once toiled  he simply said   Look where we are  Look where we are right now    This would not happen again  and everyone knew it  It was not just that there might never be another African American president of the United States  It was the feeling that this particular black family  the Obamas  represented the best of black people  the ultimate credit to the race  incomparable in elegance and bearing   There are no more   the comedian Sinbad joked back in 2010   There are no black men raised in Kansas and Hawaii  That s the last one  Y all better treat this one right  The next one gonna be from Cleveland  He gonna wear a perm  Then you gonna see what it s really like   Throughout their residency  the Obamas had refrained from showing America  what it s really like   and had instead followed the first lady s motto   When they go low  we go high   This was the ideal black and graceful under fire saluted that evening  The president was lionized as  our crown jewel   The first lady was praised as the woman  who put the O in Obama    Barack Obama s victories in 2008 and 2012 were dismissed by some of his critics as merely symbolic for African Americans  But there is nothing  mere  about symbols  The power embedded in the word nigger is also symbolic  Burning crosses do not literally raise the black poverty rate  and the Confederate flag does not directly expand the wealth gap   Much as the unbroken ranks of 43 white male presidents communicated that the highest office of government in the country indeed  the most powerful political offices in the world was off limits to black individuals  the election of Barack Obama communicated that the prohibition had been lifted  It communicated much more  Before Obama triumphed in 2008  the most famous depictions of black success tended to be entertainers or athletes  But Obama had shown that it was  possible to be smart and cool at the same damn time   as Jesse Williams put it at the BET party  Moreover  he had not embarrassed his people with a string of scandals  Against the specter of black pathology  against the narrow images of welfare moms and deadbeat dads  his time in the White House had been an eight year showcase of a healthy and successful black family spanning three generations  with two dogs to boot  In short  he became a symbol of black people s everyday  extraordinary Americanness   Whiteness in America is a different symbol a badge of advantage  In a country of professed meritocratic competition  this badge has long ensured an unerring privilege  represented in a 220 year monopoly on the highest office in the land  For some not insubstantial sector of the country  the elevation of Barack Obama communicated that the power of the badge had diminished  For eight long years  the badge holders watched him  They saw footage of the president throwing bounce passes and shooting jumpers  They saw him enter a locker room  give a businesslike handshake to a white staffer  and then greet Kevin Durant with something more soulful  They saw his wife dancing with Jimmy Fallon and posing  resplendent  on the covers of magazines that had  only a decade earlier  been almost exclusively  if unofficially  reserved for ladies imbued with the great power of the badge   For the preservation of the badge  insidious rumors were concocted to denigrate the first black White House  Obama gave free cellphones to disheveled welfare recipients  Obama went to Europe and complained that  ordinary men and women are too small minded to govern their own affairs   Obama had inscribed an Arabic saying on his wedding ring  then stopped wearing the ring  in observance of Ramadan  He canceled the National Day of Prayer  refused to sign certificates for Eagle Scouts  faked his attendance at Columbia University  and used a teleprompter to address a group of elementary school students  The badge holders fumed  They wanted their country back  And  though no one at the farewell party knew it  in a couple of weeks they would have it   On this October night  though  the stage belonged to another America  At the end of the party  Obama looked out into the crowd  searching for Dave Chappelle   Where s Dave   he cried  And then  finding him  the president referenced Chappelle s legendary Brooklyn concert   You got your block party  I got my block party   Then the band struck up Al Green s  Love and Happiness  the evening s theme  The president danced in a line next to Ronnie DeVoe  Together they mouthed the lyrics   Make you do right  Love will make you do wrong   '

No we split and count by using len()


In [57]:
words_list = article_no_punct.split()

In [58]:
words_total = len(words_list)

In [59]:
print('The total amount of words is: {}'.format(words_total))


The total amount of words is: 2143

What if we want to know how many words of each kind are?

We can do that easily by using dictionaries so:

Let's use dictionaries

To do the counting we will use dictionaries, this will allow to count how many words of each kind are in an easy way. We will also use the get(), to do the counting.


In [60]:
count = {}
for word in words_list:
        count[word] = count.get(word,0) + 1

If we print the dictionary we should have every word as a key and then next to it the value will indicate the amount of it that we have.


In [61]:
print(count)


{'hair': 1, 'embarrassed': 1, 'In': 4, 'jeans': 1, 'than': 2, 'past': 2, 'eclectic': 1, 'rapture': 1, 'go': 2, 'lit': 1, 'felt': 2, 'operatic': 1, 'brown': 1, 'Prayer': 1, 'fans': 1, 'smile': 2, 'watched': 1, 'campaigning': 1, 'searching': 1, 'school': 1, 'beat': 1, 'victory': 2, 'an': 4, 'to': 41, 'political': 1, 'months': 1, 'most': 2, 'prohibition': 1, 'were': 13, 'year': 3, 'almost': 2, 'guests': 4, 'power': 4, 'stole': 1, 'now': 2, 'free': 2, 'land': 1, 'Throughout': 1, 'performed': 1, 'if': 1, 'before': 4, 'She': 2, 'ideal': 1, 'Everything': 1, 'seniors': 1, 'Room': 1, 'his': 14, 'who': 5, 'show': 1, 'coolly': 1, 'magazines': 1, 'faked': 1, 'orange': 1, 'there': 5, 'bag': 1, 'no': 6, 'group': 2, 'Alabama': 1, 'jackets': 1, 'is': 6, 'again': 3, 'shown': 1, 'wrong': 1, 'buoy': 1, 'great': 1, 'advantage': 1, 'Americanness': 1, 'privilege': 1, 'farewell': 3, 'Together': 2, 'Entertainment': 1, 'stopped': 1, 'effort': 1, 'session': 1, 'represented': 2, 'O': 1, 'import': 2, 'tended': 1, 'Service': 2, 'ensued': 1, 'President': 2, 'mean': 1, 'not': 12, 'Clinton': 3, 'earlier': 1, 'meritocratic': 1, 'keeping': 1, 'dancing': 4, 'famous': 2, 'ruffles': 1, 'have': 4, 'success': 1, 'Campbell': 1, 'formidable': 1, '5': 1, 'sharp': 1, 'membership': 1, '55': 1, 'some': 2, 'ghost': 1, 'twist': 1, '220': 1, 'feet': 2, 'Where': 1, 'different': 1, 'waning': 1, 'ranks': 1, 'Blind': 1, 'has': 2, 'Whiteness': 1, 'Much': 1, 'shooting': 1, 'cellphones': 1, 'invited': 3, 'treat': 1, 'If': 1, 'Cleveland': 1, 'dropped': 1, 'own': 2, 'rate': 1, 'Hotline': 1, 'staffers': 1, 'sculpted': 1, 'dubbed': 1, 'gave': 1, 'This': 6, 'previous': 1, 'decade': 1, 'people': 4, 'long': 4, 'praised': 1, 'concerts': 1, 'first': 8, 'brisker': 1, 'symbol': 2, 'Rose': 1, 'queue': 1, 'launched': 1, 'American': 2, 'Gatsby': 1, 'depictions': 1, 'May': 1, 'fill': 1, 'office': 2, 'say': 1, 'we': 4, 'My': 2, 'slaves': 1, 'Blow': 1, 'attendance': 1, 'subsequent': 1, 'time': 4, 'ordinary': 1, 'Cutting': 1, 'chosen': 1, 'roundly': 1, 'Trump': 1, 'crown': 1, 'Miranda': 1, 'generations': 1, 'top': 1, '30': 1, 'others': 3, 'legendary': 1, 'one': 7, 'BET': 3, 'its': 1, 'Light': 1, 'art': 1, 'glee': 1, 'you': 4, 'seemed': 3, 'wanted': 1, 'him': 4, 'toward': 1, 'Brooklyn': 1, 'looking': 1, 'handshake': 1, 'Scott': 2, 'pride': 1, 'Stay': 1, 'opulence': 1, 'Monáe': 1, 'grown': 1, 'certificates': 1, 'performances': 1, 'low': 1, 'them': 1, 'better': 1, 'race': 1, 'presented': 1, 'awed': 1, 'loomed': 1, 'pompadour': 1, 'Common': 1, 'suits': 2, 'Kevin': 1, 'started': 1, 'raised': 1, 'Those': 1, 'withstanding': 1, 'wife': 2, 'reserved': 1, 'looked': 1, 'powerful': 1, 'series': 1, 'Obama': 19, 'Bennett': 1, 'weeks': 5, 'wear': 1, 'laughter': 1, 'highest': 2, 'Oscar': 1, 'credit': 1, 'ensemble': 1, 'Say': 1, 'us': 2, 'but': 3, 'Bob': 1, 'main': 1, 'literally': 1, 'remembered': 1, 'ensured': 1, 'Wing': 1, 'expense': 1, 'leader': 1, 'standing': 1, '2010': 1, 'LOVE': 1, 'Day': 2, 'African': 3, 'indeed': 1, 'had': 22, 'happen': 1, 'told': 1, 'healthy': 1, 'disheveled': 1, 'butt': 1, 'prevent': 1, 'rows': 1, 'playing': 1, 'confiscated': 1, 'Ta': 1, 'saluted': 1, 'type': 1, 'danced': 1, 'last': 4, 'monopoly': 1, 'telling': 1, 'refrained': 1, 'Now': 2, 'does': 1, 'hook': 1, 'room': 1, 'gap': 1, 'enormous': 1, 'Ludacris': 1, 'residence': 1, 'MAKE': 1, 'cocktail': 1, 'board': 1, 'already': 1, 'grace': 1, 'Inauguration': 1, 'twerking': 2, 'freestyled': 1, 'Jay': 1, 'ultimate': 1, 'used': 1, 'Ronnie': 1, 'excellence': 1, 'spend': 1, 'Afrika': 1, 'scandal': 1, 'pathology': 1, 'seemingly': 1, 'sign': 1, 'preservation': 1, 'stage': 4, 'La': 2, 'for': 10, 'Mavis': 1, 'insidious': 1, 'toiled': 1, 'best': 1, 'heard': 1, 'Ramadan': 1, 'Frank': 1, 'tweet': 1, 'country': 5, 'You': 2, 'Chance': 1, 'incomparable': 1, 'subjecting': 1, 'season': 1, 'later': 1, 'security': 3, 'Columbia': 1, 'unerring': 1, 'throwing': 2, 'preceding': 1, 'she': 2, 'lyrics': 1, 'Legend': 1, 'ballad': 1, 'imbued': 1, 'coinworthy': 1, 'pocket': 1, 'trolley': 1, 'fades': 1, 'minded': 1, 'nothing': 1, 're': 2, 'On': 1, 'm': 3, 'ties': 2, 'voted': 1, 'Cellphones': 1, 'uncle': 1, '80s': 1, 'suggest': 1, 'spent': 1, 'worth': 1, 'name': 1, 'communicated': 4, 'two': 3, 'elevation': 1, 'remotely': 1, 'South': 2, 'much': 2, 'Treasury': 1, 'DJ': 1, 'evening': 3, 'said': 7, 'stand': 1, 'tradition': 1, 'presidents': 1, 'entertainers': 1, 'against': 1, 'companion': 1, 'threat': 1, 'limits': 1, 'Train': 1, 'welcomed': 1, 'least': 1, 'large': 1, 'poverty': 1, 'Rhymes': 1, 'greeted': 1, 'Gentlemen': 1, 'address': 1, 'That': 2, 'sun': 1, 'They': 8, 'possible': 1, 'elegance': 1, 'inaugurating': 1, 'done': 1, 'University': 1, 'But': 4, 'teleprompter': 1, 'sang': 1, 'directly': 1, 'election': 1, 'damn': 2, 'backgrounds': 1, 'Drake': 1, 'opening': 1, 'Great': 1, 'actor': 1, 'Yolanda': 1, 'where': 5, 'word': 2, 'wealth': 1, 'saying': 1, 'coats': 1, 'good': 2, 'week': 1, 'optional': 1, 'favorite': 1, 'next': 4, 'guest': 1, 'curls': 1, 'full': 2, 'laughed': 1, 'moms': 1, 'crowd': 8, 'back': 5, 'individuals': 1, 'blooming': 1, 'brought': 1, 'loudspeakers': 1, 'struck': 1, 'birthed': 1, 'Several': 1, 'Make': 1, 'stepped': 1, 'dreads': 1, 'family': 2, 'Beatz': 1, 'unedited': 1, 'at': 14, 'late': 1, 'Beyoncé': 1, 'October': 4, 'whole': 1, 'fountain': 1, 'turned': 1, 'mix': 2, 'YOU': 1, 'hosted': 4, 'never': 3, 'media': 1, 'draws': 2, 'welfare': 2, 'end': 1, 'rally': 1, 'spanning': 1, 'sitting': 1, 'skinned': 1, 'younger': 1, 'showcase': 1, 'inevitable': 1, 'behind': 1, 'lethargy': 1, 'inside': 1, 'I': 8, 'rock': 1, 'simply': 1, 'flash': 1, 'years': 2, 'Tony': 1, 'on': 12, 'tops': 1, 'my': 1, 'fumed': 1, 'close': 1, 'each': 1, 'followed': 1, 'Biv': 1, 'initiatives': 1, 'diminished': 1, 'Adams': 1, 'wearing': 1, 'too': 1, 'rotten': 1, 'off': 3, 'explained': 1, 'was': 23, 'wind': 1, 'coin': 1, 'right': 4, 'unsuccessful': 1, 'tonight': 1, 'woman': 1, 'bamboo': 1, 'particular': 1, 'mouthed': 1, 'surely': 1, 'performance': 1, 'among': 1, 'still': 4, 'been': 6, 'fur': 1, '2011': 1, 'America': 4, 'Kennedys': 1, 'Kool': 1, 'deadbeat': 1, 'he': 13, 'usual': 1, 'tell': 1, 'Pennsylvania': 1, 'with': 15, 'gorgeous': 1, 'referenced': 1, 'will': 2, 'laughing': 1, 'discuss': 1, 'make': 2, 'loafers': 1, 'made': 1, 'rapper': 2, 'someday': 1, 'cried': 1, 'hummed': 1, 'small': 2, 'Guests': 1, 'lovely': 1, 'ever': 1, 'giant': 1, 'chivalrously': 1, 'And': 4, 'Usher': 1, 'string': 1, 'comedy': 1, 'men': 3, 'history': 2, 'insubstantial': 1, 'concert': 2, 'Eagle': 1, 'sides': 1, 'Allen': 1, 'another': 2, 'also': 2, '2012': 1, 'your': 2, 'they': 7, 'using': 1, 'front': 2, 's': 22, 'ring': 2, 'shaved': 1, 'behavior': 1, 'Fallon': 1, 'merely': 1, 'same': 1, 'boot': 1, 'Three': 1, 'jumpers': 1, 'Photograph': 1, 'advantages': 1, 'United': 1, 'fire': 1, 'WRONG': 1, 'Bronx': 1, 'DeVoe': 2, 'which': 1, 'naturals': 1, 'historical': 1, 'boys': 1, 'It': 5, 'days': 2, 'night': 6, 'their': 10, 'count': 1, 'exclusively': 1, 'footage': 1, 'really': 2, 'just': 2, 'over': 2, 'businesslike': 1, 'might': 1, 'motto': 1, 'government': 1, 'pussygate': 1, 'Jesse': 2, 'fracas': 1, 'Black': 2, 'Hillary': 1, 'party': 7, '21st': 1, 'refused': 1, 'loud': 1, 'see': 1, 'introducing': 1, 'earrings': 1, 'crosses': 1, 'going': 1, 'cracking': 1, 'these': 2, 'professed': 1, 'rumors': 1, 'Sinbad': 1, 'Hawaii': 1, 'enter': 1, 'gospel': 1, 'proper': 1, 'primarily': 1, 'Everyone': 1, 'remained': 1, 'boarded': 1, 'from': 9, 'trio': 1, 'by': 8, 'can': 1, 'States': 1, 'the': 144, 'passes': 1, 'surreptitious': 1, 'bus': 1, 'jewel': 1, 'statement': 1, 'band': 2, 'in': 47, 'Rapper': 1, 'slight': 1, 'fellow': 1, 'male': 1, 'big': 1, 'saw': 3, 'burning': 1, 'Boys': 1, 'arrive': 1, 'put': 3, 'proud': 1, 'concocted': 1, 'dogs': 1, 'singer': 2, 'elementary': 1, 'Was': 1, 'denigrate': 1, 'watching': 1, '6': 1, 'Nehisi': 1, 'He': 5, 'graduating': 1, 'stretched': 1, 'Then': 3, 'Obamas': 4, 'it': 12, 'call': 1, 'such': 2, 'lifted': 1, 'The': 26, 'sockless': 1, 'hit': 1, 'grasp': 1, 'shivered': 1, 'along': 1, 'New': 1, 'black': 19, 'be': 10, 'across': 2, 'crucial': 1, 'specter': 1, 'handed': 1, 'form': 1, 'competition': 1, 'pass': 1, 'should': 1, 'everything': 1, 'Staples': 1, 'Swizz': 1, 'flag': 1, 'presidential': 2, 'style': 1, 'Jimmy': 1, 'Y': 1, 'York': 1, 'Virginia': 1, 'Dave': 3, 'athletes': 1, 'When': 2, 'affairs': 1, 'National': 1, 'opponents': 1, 'went': 1, 'second': 1, 'trust': 1, 'Scouts': 1, 'wait': 1, 'bunch': 1, 'lawn': 1, 'out': 4, 'artists': 1, 'cards': 2, 'asked': 1, 'unbroken': 2, 'roared': 2, 'mere': 1, 'and': 58, 'invulnerable': 1, 'our': 1, 'Durant': 1, 'assembled': 1, 'fervent': 1, 'guy': 1, 'offices': 1, 'all': 3, 'became': 1, 'couple': 2, 'Before': 1, 'many': 1, 'Secret': 2, 'inscribed': 1, 'white': 2, 'recordings': 1, 'crisp': 1, 'Look': 2, 'strongholds': 1, 'a': 49, 'dinner': 1, 'prospect': 1, 'criminal': 1, 'graceful': 1, 'event': 2, 'blond': 1, 'making': 1, 'administration': 1, 'Things': 1, 'could': 1, 'potential': 1, 'observance': 1, 'day': 1, 'must': 1, 'Donald': 1, 'lady': 2, 'stood': 1, '2008': 2, 'eight': 3, 'between': 1, 'creator': 1, 'succession': 1, 'heels': 1, 'nominee': 1, 'green': 1, 'music': 1, 'promise': 1, 'barrage': 1, 'world': 3, 'once': 3, 'Not': 1, 'tight': 1, 'East': 1, 'light': 1, 'joked': 2, 'Burning': 1, 'criticized': 1, 'locker': 1, 'came': 1, 'or': 2, 'Chappelle': 4, 'Busta': 1, 'Kansas': 1, 'Texas': 1, 'pen': 2, 'presidency': 2, 'try': 1, 'Lin': 1, 'though': 2, 'musical': 1, 'accentuate': 1, 'Jill': 1, 'None': 1, 'while': 1, 'triumphed': 1, 'adding': 1, 'perm': 1, 'F': 1, 'posing': 1, 'her': 5, 'tent': 1, 'actress': 1, 'led': 1, '43': 1, 'hop': 5, 'states': 1, 'contemporaries': 1, 'Americans': 2, 'genuine': 1, 'Well': 1, 'early': 1, 'badge': 7, 'recipients': 1, 'flourishes': 1, 'older': 1, 'symbols': 1, 'Ian': 1, 'symbolic': 3, 'Michelle': 1, 'Europe': 1, 'as': 11, 'other': 1, 'narrow': 1, 'wing': 1, 'feeling': 1, 'foundational': 1, 'nigger': 1, 'sense': 2, 'fall': 1, 'dark': 1, 'checking': 1, 'jokes': 1, 'solid': 1, 'residency': 1, 'Bambaataa': 1, 'anyway': 1, 'bounce': 1, 'wary': 1, 'Bell': 1, 'into': 6, 'Bling': 1, 'dresses': 1, 'louder': 1, 'everyone': 2, 'number': 1, 'flashed': 1, 'lines': 2, 'Coates': 1, 'under': 2, 'generation': 1, 'together': 1, 'White': 10, 'John': 1, 'glorious': 1, 'GOP': 1, 'Manuel': 1, 'of': 58, 'got': 2, 'For': 3, 'home': 1, 'dads': 1, 'Republican': 1, 'House': 10, 'gold': 1, 'when': 2, 'classic': 1, 'makeshift': 1, 'wedding': 1, 'only': 2, 'give': 1, 'so': 1, 'B': 1, 'theme': 1, 'There': 5, 'gonna': 3, 'A': 2, 'Herc': 1, 'Glory': 1, 'would': 6, 'names': 1, 'fantastic': 1, 'De': 2, 'comedian': 1, 'man': 1, 'up': 3, 'Soul': 2, 'distance': 1, 'did': 4, 'three': 2, 'ushered': 1, 'audience': 1, 'perform': 1, 'grand': 1, 'Garden': 1, 'down': 2, 'everyday': 1, 'smart': 1, 'showed': 2, 'young': 1, 'showing': 1, 'leaking': 1, 'community': 1, 'reflected': 1, 'Naomi': 1, 'Polls': 1, 'bearing': 1, 'Gumby': 1, 'suit': 1, 'Arabic': 1, 'After': 2, 'took': 2, 'moment': 1, 'trolleys': 1, 'belonged': 2, 'winning': 1, 'what': 5, 'something': 1, 'about': 3, 'me': 1, 'play': 1, 'peril': 1, 'expand': 1, 'state': 1, 'beginning': 1, 'video': 1, 'embedded': 1, 'Dylan': 1, 'becoming': 1, 'partygoer': 1, 'Drop': 1, 'social': 1, 'holders': 2, 'paper': 1, 'Green': 2, 'begun': 1, 'dismissed': 1, 'reform': 1, 'song': 2, 'seat': 1, 'pioneering': 1, 'resplendent': 1, 'passing': 1, 'checked': 1, 'Band': 1, 'WILL': 1, 'student': 1, 'gray': 1, 'set': 1, 'placed': 1, 'By': 2, 'greet': 1, 'women': 2, 'short': 1, 'knew': 2, 'At': 4, 'boyish': 1, 'Confederate': 1, 'high': 3, 'lights': 1, 'justice': 1, 'sleeveless': 1, 'unofficially': 1, 'cool': 1, 'like': 7, 'victories': 1, 'Orlando': 1, 'ladies': 1, 'extraordinary': 1, 'Let': 1, 'being': 1, '28': 1, 'Love': 2, 'Kurtis': 1, 'Outstanding': 1, 'feel': 1, 'way': 1, 'soulful': 1, 'p': 1, 'Janelle': 1, 'Al': 2, 'Hamilton': 1, 'hip': 6, 'age': 1, 'Gap': 1, 'moved': 1, 'Friday': 1, 'finding': 1, 'humor': 1, 'few': 2, 'come': 2, 'Against': 1, 'Z': 1, 'blue': 2, 'are': 8, 'scandals': 1, 'president': 7, 'test': 1, 'Lawn': 2, 'successful': 1, 'lionized': 1, 'noting': 2, 'staffer': 1, 'Barack': 4, 'this': 9, 'Georgia': 1, 'sector': 1, 'hecklers': 1, 'strolled': 2, 'Television': 1, 'Democratic': 1, 'then': 8, 'images': 1, 'Ocean': 1, 'raise': 1, 'students': 1, 'Williams': 2, 'longing': 1, 'Moreover': 1, 'shouted': 1, 'college': 1, 'cuffed': 1, 'complained': 1, 'line': 3, 'chops': 1, 'more': 3, 'govern': 1, 'covers': 1, 'Fitzgerald': 1, 'Women': 1, 'block': 2, 'response': 1, 'critics': 1, 'instead': 1, 'Building': 1, 'do': 4, 'Happiness': 1, 'DO': 1, 'that': 15, 'canceled': 1, 'suede': 1}

How many sentences are in part one?

If you take a look at the article you might have noticed that the header sentences have no '.' but there are break lines there, so we will replace the '\n' for periods and then but split.


In [62]:
#We will modify article_sentences but we want to keep intact article. So
article_sentences = article

In [63]:
article_sentences = article_sentences.replace('\n','.')

In [64]:
sentences_article_list = article_sentences.split('.')

In [65]:
print(sentences_article_list)


['My President Was Black', 'A history of the first African American White House—and of what came next', '', 'By Ta-Nehisi Coates', 'Photograph by Ian Allen', '', '“They’re a rotten crowd,” I shouted across the lawn', ' “You’re worth the whole damn bunch put together', '”', '', '— F', ' Scott Fitzgerald, The Great Gatsby', '', 'I', ' “LOVE WILL MAKE YOU DO WRONG”', '', 'In the waning days of President Barack Obama’s administration, he and his wife, Michelle, hosted a farewell party, the full import of which no one could then grasp', ' It was late October, Friday the 21st, and the president had spent many of the previous weeks, as he would spend the two subsequent weeks, campaigning for the Democratic presidential nominee, Hillary Clinton', ' Things were looking up', ' Polls in the crucial states of Virginia and Pennsylvania showed Clinton with solid advantages', ' The formidable GOP strongholds of Georgia and Texas were said to be under threat', ' The moment seemed to buoy Obama', ' He had been light on his feet in these last few weeks, cracking jokes at the expense of Republican opponents and laughing off hecklers', ' At a rally in Orlando on October 28, he greeted a student who would be introducing him by dancing toward her and then noting that the song playing over the loudspeakers—the Gap Band’s “Outstanding”—was older than she was', ' “This is classic!” he said', ' Then he flashed the smile that had launched America’s first black presidency, and started dancing again', ' Three months still remained before Inauguration Day, but staffers had already begun to count down the days', ' They did this with a mix of pride and longing—like college seniors in early May', ' They had no sense of the world they were graduating into', ' None of us did', '', '', 'The farewell party, presented by BET (Black Entertainment Television), was the last in a series of concerts the first couple had hosted at the White House', ' Guests were asked to arrive at 5:30 p', 'm', ' By 6, two long lines stretched behind the Treasury Building, where the Secret Service was checking names', ' The people in these lines were, in the main, black, and their humor reflected it', ' The brisker queue was dubbed the “good-hair line” by one guest, and there was laughter at the prospect of the Secret Service subjecting us all to a “brown-paper-bag test', '” This did not come to pass, but security was tight', ' Several guests were told to stand in a makeshift pen and wait to have their backgrounds checked a second time', '', '', 'Dave Chappelle was there', ' He coolly explained the peril and promise of comedy in what was then still only a remotely potential Donald Trump presidency: “I mean, we never had a guy have his own pussygate scandal', '” Everyone laughed', ' A few weeks later, he would be roundly criticized for telling a crowd at the Cutting Room, in New York, that he had voted for Clinton but did not feel good about it', ' “She’s going to be on a coin someday,” Chappelle said', ' “And her behavior has not been coinworthy', '” But on this crisp October night, everything felt inevitable and grand', ' There was a slight wind', ' It had been in the 80s for much of that week', ' Now, as the sun set, the season remembered its name', ' Women shivered in their cocktail dresses', ' Gentlemen chivalrously handed over their suit coats', ' But when Naomi Campbell strolled past the security pen in a sleeveless number, she seemed as invulnerable as ever', '', '', 'Cellphones were confiscated to prevent surreptitious recordings from leaking out', ' (This effort was unsuccessful', ' The next day, a partygoer would tweet a video of the leader of the free world dancing to Drake’s “Hotline Bling', '”) After withstanding the barrage of security, guests were welcomed into the East Wing of the White House, and then ushered back out into the night, where they boarded a succession of orange-and-green trolleys', ' The singer and actress Janelle Monáe, her famous and fantastic pompadour preceding her, stepped on board and joked with a companion about the historical import of “sitting in the back of the bus', '” She took a seat three rows from the front and hummed into the night', ' The trolley dropped the guests on the South Lawn, in front of a giant tent', ' The South Lawn’s fountain was lit up with blue lights', ' The White House proper loomed like a ghost in the distance', ' I heard the band, inside, beginning to play Al Green’s “Let’s Stay Together', '”', '', '“Well, you can tell what type of night this is,” Obama said from the stage, opening the event', ' “Not the usual ruffles and flourishes!”', '', 'The crowd roared', '', '', '“This must be a BET event!”', '', 'The crowd roared louder still', '', '', 'Obama placed the concert in the White House’s musical tradition, noting that guests of the Kennedys had once done the twist at the residence—“the twerking of their time,” he said, before adding, “There will be no twerking tonight', ' At least not by me', '”', '', 'The Obamas are fervent and eclectic music fans', ' In the past eight years, they have hosted performances at the White House by everyone from Mavis Staples to Bob Dylan to Tony Bennett to the Blind Boys of Alabama', ' After the rapper Common was invited to perform in 2011, a small fracas ensued in the right-wing media', ' He performed anyway—and was invited back again this glorious fall evening and almost stole the show', ' The crowd sang along to the hook for his hit ballad “The Light', '” And when he brought on the gospel singer Yolanda Adams to fill in for John Legend on the Oscar-winning song “Glory,” glee turned to rapture', '', '', 'De La Soul was there', ' The hip-hop trio had come of age as boyish B-boys with Gumby-style high-top fades', ' Now they moved across the stage with a lovely mix of lethargy and grace, like your favorite uncle making his way down the Soul Train line, wary of throwing out a hip', ' I felt a sense of victory watching them rock the crowd, all while keeping it in the pocket', ' The victory belonged to hip-hop—an art form birthed in the burning Bronx and now standing full grown, at the White House, unbroken and unedited', ' Usher led the crowd in a call-and-response: “Say it loud, I’m black and I’m proud', '” Jill Scott showed off her operatic chops', ' Bell Biv DeVoe, contemporaries of De La, made history with their performance by surely becoming the first group to suggest to a presidential audience that one should “never trust a big butt and a smile', '”', '', 'The ties between the Obama White House and the hip-hop community are genuine', ' The Obamas are social with Beyoncé and Jay-Z', ' They hosted Chance the Rapper and Frank Ocean at a state dinner, and last year invited Swizz Beatz, Busta Rhymes, and Ludacris, among others, to discuss criminal-justice reform and other initiatives', ' Obama once stood in the Rose Garden passing large flash cards to the Hamilton creator and rapper Lin-Manuel Miranda, who then freestyled using each word on the cards', ' “Drop the beat,” Obama said, inaugurating the session', ' At 55, Obama is younger than pioneering hip-hop artists like Afrika Bambaataa, DJ Kool Herc, and Kurtis Blow', ' If Obama’s enormous symbolic power draws primarily from being the country’s first black president, it also draws from his membership in hip-hop’s foundational generation', '', '', 'That night, the men were sharp in their gray or black suits and optional ties', ' Those who were not in suits had chosen to make a statement, like the dark-skinned young man who strolled in, sockless, with blue jeans cuffed so as to accentuate his gorgeous black-suede loafers', ' Everything in his ensemble seemed to say, “My fellow Americans, do not try this at home', '” There were women in fur jackets and high heels; others with sculpted naturals, the sides shaved close, the tops blooming into curls; others still in gold bamboo earrings and long blond dreads', ' When the actor Jesse Williams took the stage, seemingly awed before such black excellence, before such black opulence, assembled just feet from where slaves had once toiled, he simply said, “Look where we are', ' Look where we are right now', '”', '', 'This would not happen again, and everyone knew it', ' It was not just that there might never be another African American president of the United States', ' It was the feeling that this particular black family, the Obamas, represented the best of black people, the ultimate credit to the race, incomparable in elegance and bearing', ' “There are no more,” the comedian Sinbad joked back in 2010', ' “There are no black men raised in Kansas and Hawaii', ' That’s the last one', ' Y’all better treat this one right', ' The next one gonna be from Cleveland', ' He gonna wear a perm', ' Then you gonna see what it’s really like', '” Throughout their residency, the Obamas had refrained from showing America “what it’s really like,” and had instead followed the first lady’s motto, “When they go low, we go high', '” This was the ideal—black and graceful under fire—saluted that evening', ' The president was lionized as “our crown jewel', '” The first lady was praised as the woman “who put the O in Obama', '”', '', 'Barack Obama’s victories in 2008 and 2012 were dismissed by some of his critics as merely symbolic for African Americans', ' But there is nothing “mere” about symbols', ' The power embedded in the word nigger is also symbolic', ' Burning crosses do not literally raise the black poverty rate, and the Confederate flag does not directly expand the wealth gap', '', '', 'Much as the unbroken ranks of 43 white male presidents communicated that the highest office of government in the country—indeed, the most powerful political offices in the world—was off-limits to black individuals, the election of Barack Obama communicated that the prohibition had been lifted', ' It communicated much more', ' Before Obama triumphed in 2008, the most-famous depictions of black success tended to be entertainers or athletes', ' But Obama had shown that it was “possible to be smart and cool at the same damn time,” as Jesse Williams put it at the BET party', ' Moreover, he had not embarrassed his people with a string of scandals', ' Against the specter of black pathology, against the narrow images of welfare moms and deadbeat dads, his time in the White House had been an eight-year showcase of a healthy and successful black family spanning three generations, with two dogs to boot', ' In short, he became a symbol of black people’s everyday, extraordinary Americanness', '', '', 'Whiteness in America is a different symbol—a badge of advantage', ' In a country of professed meritocratic competition, this badge has long ensured an unerring privilege, represented in a 220-year monopoly on the highest office in the land', ' For some not-insubstantial sector of the country, the elevation of Barack Obama communicated that the power of the badge had diminished', ' For eight long years, the badge-holders watched him', ' They saw footage of the president throwing bounce passes and shooting jumpers', ' They saw him enter a locker room, give a businesslike handshake to a white staffer, and then greet Kevin Durant with something more soulful', ' They saw his wife dancing with Jimmy Fallon and posing, resplendent, on the covers of magazines that had, only a decade earlier, been almost exclusively, if unofficially, reserved for ladies imbued with the great power of the badge', '', '', 'For the preservation of the badge, insidious rumors were concocted to denigrate the first black White House', ' Obama gave free cellphones to disheveled welfare recipients', ' Obama went to Europe and complained that “ordinary men and women are too small-minded to govern their own affairs', '” Obama had inscribed an Arabic saying on his wedding ring, then stopped wearing the ring, in observance of Ramadan', ' He canceled the National Day of Prayer; refused to sign certificates for Eagle Scouts; faked his attendance at Columbia University; and used a teleprompter to address a group of elementary-school students', ' The badge-holders fumed', ' They wanted their country back', ' And, though no one at the farewell party knew it, in a couple of weeks they would have it', '', '', 'On this October night, though, the stage belonged to another America', ' At the end of the party, Obama looked out into the crowd, searching for Dave Chappelle', ' “Where’s Dave?” he cried', ' And then, finding him, the president referenced Chappelle’s legendary Brooklyn concert', ' “You got your block party', ' I got my block party', '” Then the band struck up Al Green’s “Love and Happiness”—the evening’s theme', ' The president danced in a line next to Ronnie DeVoe', ' Together they mouthed the lyrics: “Make you do right', ' Love will make you do wrong', '”', '']

Let's ommit the '' and the elements that are "sentences" that are actually two letters because they were part of an abbreviation. For example '— F' or '"'. These elements have the particularity that their length is always smaller than 3, so let's filter that.


In [66]:
list_clean = list(filter(lambda item: len(item)>3 , sentences_article_list))

In [67]:
print(list_clean)


['My President Was Black', 'A history of the first African American White House—and of what came next', 'By Ta-Nehisi Coates', 'Photograph by Ian Allen', '“They’re a rotten crowd,” I shouted across the lawn', ' “You’re worth the whole damn bunch put together', ' Scott Fitzgerald, The Great Gatsby', ' “LOVE WILL MAKE YOU DO WRONG”', 'In the waning days of President Barack Obama’s administration, he and his wife, Michelle, hosted a farewell party, the full import of which no one could then grasp', ' It was late October, Friday the 21st, and the president had spent many of the previous weeks, as he would spend the two subsequent weeks, campaigning for the Democratic presidential nominee, Hillary Clinton', ' Things were looking up', ' Polls in the crucial states of Virginia and Pennsylvania showed Clinton with solid advantages', ' The formidable GOP strongholds of Georgia and Texas were said to be under threat', ' The moment seemed to buoy Obama', ' He had been light on his feet in these last few weeks, cracking jokes at the expense of Republican opponents and laughing off hecklers', ' At a rally in Orlando on October 28, he greeted a student who would be introducing him by dancing toward her and then noting that the song playing over the loudspeakers—the Gap Band’s “Outstanding”—was older than she was', ' “This is classic!” he said', ' Then he flashed the smile that had launched America’s first black presidency, and started dancing again', ' Three months still remained before Inauguration Day, but staffers had already begun to count down the days', ' They did this with a mix of pride and longing—like college seniors in early May', ' They had no sense of the world they were graduating into', ' None of us did', 'The farewell party, presented by BET (Black Entertainment Television), was the last in a series of concerts the first couple had hosted at the White House', ' Guests were asked to arrive at 5:30 p', ' By 6, two long lines stretched behind the Treasury Building, where the Secret Service was checking names', ' The people in these lines were, in the main, black, and their humor reflected it', ' The brisker queue was dubbed the “good-hair line” by one guest, and there was laughter at the prospect of the Secret Service subjecting us all to a “brown-paper-bag test', '” This did not come to pass, but security was tight', ' Several guests were told to stand in a makeshift pen and wait to have their backgrounds checked a second time', 'Dave Chappelle was there', ' He coolly explained the peril and promise of comedy in what was then still only a remotely potential Donald Trump presidency: “I mean, we never had a guy have his own pussygate scandal', '” Everyone laughed', ' A few weeks later, he would be roundly criticized for telling a crowd at the Cutting Room, in New York, that he had voted for Clinton but did not feel good about it', ' “She’s going to be on a coin someday,” Chappelle said', ' “And her behavior has not been coinworthy', '” But on this crisp October night, everything felt inevitable and grand', ' There was a slight wind', ' It had been in the 80s for much of that week', ' Now, as the sun set, the season remembered its name', ' Women shivered in their cocktail dresses', ' Gentlemen chivalrously handed over their suit coats', ' But when Naomi Campbell strolled past the security pen in a sleeveless number, she seemed as invulnerable as ever', 'Cellphones were confiscated to prevent surreptitious recordings from leaking out', ' (This effort was unsuccessful', ' The next day, a partygoer would tweet a video of the leader of the free world dancing to Drake’s “Hotline Bling', '”) After withstanding the barrage of security, guests were welcomed into the East Wing of the White House, and then ushered back out into the night, where they boarded a succession of orange-and-green trolleys', ' The singer and actress Janelle Monáe, her famous and fantastic pompadour preceding her, stepped on board and joked with a companion about the historical import of “sitting in the back of the bus', '” She took a seat three rows from the front and hummed into the night', ' The trolley dropped the guests on the South Lawn, in front of a giant tent', ' The South Lawn’s fountain was lit up with blue lights', ' The White House proper loomed like a ghost in the distance', ' I heard the band, inside, beginning to play Al Green’s “Let’s Stay Together', '“Well, you can tell what type of night this is,” Obama said from the stage, opening the event', ' “Not the usual ruffles and flourishes!”', 'The crowd roared', '“This must be a BET event!”', 'The crowd roared louder still', 'Obama placed the concert in the White House’s musical tradition, noting that guests of the Kennedys had once done the twist at the residence—“the twerking of their time,” he said, before adding, “There will be no twerking tonight', ' At least not by me', 'The Obamas are fervent and eclectic music fans', ' In the past eight years, they have hosted performances at the White House by everyone from Mavis Staples to Bob Dylan to Tony Bennett to the Blind Boys of Alabama', ' After the rapper Common was invited to perform in 2011, a small fracas ensued in the right-wing media', ' He performed anyway—and was invited back again this glorious fall evening and almost stole the show', ' The crowd sang along to the hook for his hit ballad “The Light', '” And when he brought on the gospel singer Yolanda Adams to fill in for John Legend on the Oscar-winning song “Glory,” glee turned to rapture', 'De La Soul was there', ' The hip-hop trio had come of age as boyish B-boys with Gumby-style high-top fades', ' Now they moved across the stage with a lovely mix of lethargy and grace, like your favorite uncle making his way down the Soul Train line, wary of throwing out a hip', ' I felt a sense of victory watching them rock the crowd, all while keeping it in the pocket', ' The victory belonged to hip-hop—an art form birthed in the burning Bronx and now standing full grown, at the White House, unbroken and unedited', ' Usher led the crowd in a call-and-response: “Say it loud, I’m black and I’m proud', '” Jill Scott showed off her operatic chops', ' Bell Biv DeVoe, contemporaries of De La, made history with their performance by surely becoming the first group to suggest to a presidential audience that one should “never trust a big butt and a smile', 'The ties between the Obama White House and the hip-hop community are genuine', ' The Obamas are social with Beyoncé and Jay-Z', ' They hosted Chance the Rapper and Frank Ocean at a state dinner, and last year invited Swizz Beatz, Busta Rhymes, and Ludacris, among others, to discuss criminal-justice reform and other initiatives', ' Obama once stood in the Rose Garden passing large flash cards to the Hamilton creator and rapper Lin-Manuel Miranda, who then freestyled using each word on the cards', ' “Drop the beat,” Obama said, inaugurating the session', ' At 55, Obama is younger than pioneering hip-hop artists like Afrika Bambaataa, DJ Kool Herc, and Kurtis Blow', ' If Obama’s enormous symbolic power draws primarily from being the country’s first black president, it also draws from his membership in hip-hop’s foundational generation', 'That night, the men were sharp in their gray or black suits and optional ties', ' Those who were not in suits had chosen to make a statement, like the dark-skinned young man who strolled in, sockless, with blue jeans cuffed so as to accentuate his gorgeous black-suede loafers', ' Everything in his ensemble seemed to say, “My fellow Americans, do not try this at home', '” There were women in fur jackets and high heels; others with sculpted naturals, the sides shaved close, the tops blooming into curls; others still in gold bamboo earrings and long blond dreads', ' When the actor Jesse Williams took the stage, seemingly awed before such black excellence, before such black opulence, assembled just feet from where slaves had once toiled, he simply said, “Look where we are', ' Look where we are right now', 'This would not happen again, and everyone knew it', ' It was not just that there might never be another African American president of the United States', ' It was the feeling that this particular black family, the Obamas, represented the best of black people, the ultimate credit to the race, incomparable in elegance and bearing', ' “There are no more,” the comedian Sinbad joked back in 2010', ' “There are no black men raised in Kansas and Hawaii', ' That’s the last one', ' Y’all better treat this one right', ' The next one gonna be from Cleveland', ' He gonna wear a perm', ' Then you gonna see what it’s really like', '” Throughout their residency, the Obamas had refrained from showing America “what it’s really like,” and had instead followed the first lady’s motto, “When they go low, we go high', '” This was the ideal—black and graceful under fire—saluted that evening', ' The president was lionized as “our crown jewel', '” The first lady was praised as the woman “who put the O in Obama', 'Barack Obama’s victories in 2008 and 2012 were dismissed by some of his critics as merely symbolic for African Americans', ' But there is nothing “mere” about symbols', ' The power embedded in the word nigger is also symbolic', ' Burning crosses do not literally raise the black poverty rate, and the Confederate flag does not directly expand the wealth gap', 'Much as the unbroken ranks of 43 white male presidents communicated that the highest office of government in the country—indeed, the most powerful political offices in the world—was off-limits to black individuals, the election of Barack Obama communicated that the prohibition had been lifted', ' It communicated much more', ' Before Obama triumphed in 2008, the most-famous depictions of black success tended to be entertainers or athletes', ' But Obama had shown that it was “possible to be smart and cool at the same damn time,” as Jesse Williams put it at the BET party', ' Moreover, he had not embarrassed his people with a string of scandals', ' Against the specter of black pathology, against the narrow images of welfare moms and deadbeat dads, his time in the White House had been an eight-year showcase of a healthy and successful black family spanning three generations, with two dogs to boot', ' In short, he became a symbol of black people’s everyday, extraordinary Americanness', 'Whiteness in America is a different symbol—a badge of advantage', ' In a country of professed meritocratic competition, this badge has long ensured an unerring privilege, represented in a 220-year monopoly on the highest office in the land', ' For some not-insubstantial sector of the country, the elevation of Barack Obama communicated that the power of the badge had diminished', ' For eight long years, the badge-holders watched him', ' They saw footage of the president throwing bounce passes and shooting jumpers', ' They saw him enter a locker room, give a businesslike handshake to a white staffer, and then greet Kevin Durant with something more soulful', ' They saw his wife dancing with Jimmy Fallon and posing, resplendent, on the covers of magazines that had, only a decade earlier, been almost exclusively, if unofficially, reserved for ladies imbued with the great power of the badge', 'For the preservation of the badge, insidious rumors were concocted to denigrate the first black White House', ' Obama gave free cellphones to disheveled welfare recipients', ' Obama went to Europe and complained that “ordinary men and women are too small-minded to govern their own affairs', '” Obama had inscribed an Arabic saying on his wedding ring, then stopped wearing the ring, in observance of Ramadan', ' He canceled the National Day of Prayer; refused to sign certificates for Eagle Scouts; faked his attendance at Columbia University; and used a teleprompter to address a group of elementary-school students', ' The badge-holders fumed', ' They wanted their country back', ' And, though no one at the farewell party knew it, in a couple of weeks they would have it', 'On this October night, though, the stage belonged to another America', ' At the end of the party, Obama looked out into the crowd, searching for Dave Chappelle', ' “Where’s Dave?” he cried', ' And then, finding him, the president referenced Chappelle’s legendary Brooklyn concert', ' “You got your block party', ' I got my block party', '” Then the band struck up Al Green’s “Love and Happiness”—the evening’s theme', ' The president danced in a line next to Ronnie DeVoe', ' Together they mouthed the lyrics: “Make you do right', ' Love will make you do wrong']

In [68]:
sentence_total = len(list_clean)

In [69]:
print('The total amount of sentences is: {}'.format(sentence_total))


The total amount of sentences is: 136

Which words follow 'black' and 'white' in the text? Which ones are used the most for each?

Using our words_list, which is in order of appearance in the text, we will make two different list with the words that follow 'white' and the ones that follow 'black'. Once we have those lists we will make a dictionary counting the repetitions of each word and finally we will look for the maxium value and its corresponding key.

Finding the indices where the word white/black appears

We will make all the words lower case so we can just look for the lower case words and not worry about syntax.

The we will use two new things to complete the task, enumerate() and list comprehensions, you can read about the last one here in section 5.1.4.


In [70]:
words_lower = []
for word in words_list:
    words_lower.append(word.lower())

We want to know were in the list appears the word white and where the word black. We look for those indices doing the following.


In [71]:
indx_white  = [i for i, x in enumerate(words_lower) if x == "white"]
indx_black  = [i for i, x in enumerate(words_lower) if x == "black"]

In [72]:
print('idx white:\n',indx_white)
print('idx black:\n',indx_black)


idx white:
 [11, 317, 633, 727, 796, 854, 1042, 1113, 1624, 1745, 1876, 1940]
idx black:
 [3, 239, 299, 355, 1061, 1233, 1257, 1294, 1357, 1361, 1418, 1426, 1453, 1528, 1603, 1650, 1678, 1729, 1758, 1775, 1939]

Let's look for the word that follows each repetition of white/black and save them into lists.


In [73]:
#Looking for the words that follow white
lst_white =[]
for i in indx_white:
    lst_white.append(words_lower[i+1])

In [74]:
#Looking for the words that follow white
lst_black =[]
for i in indx_black:
    lst_black.append(words_lower[i+1])

In [75]:
print('Words that follows white:\n',lst_white)
print('Words that follows black:\n',lst_black)


Words that follows white:
 ['house', 'house', 'house', 'house', 'house', 'house', 'house', 'house', 'male', 'house', 'staffer', 'house']
Words that follows black:
 ['a', 'presidency', 'entertainment', 'and', 'and', 'president', 'suits', 'suede', 'excellence', 'opulence', 'family', 'people', 'men', 'and', 'poverty', 'individuals', 'success', 'pathology', 'family', 'people', 'white']

Let's count for each list the repetitions of each word using dictionaries and the get method.


In [76]:
follows_white = {}
for word in lst_white:
        follows_white[word] = follows_white.get(word,0) + 1

In [77]:
print(follows_white)


{'staffer': 1, 'male': 1, 'house': 10}

In [78]:
follows_black = {}
for word in lst_black:
        follows_black[word] = follows_black.get(word,0) + 1

In [79]:
print(follows_black)


{'family': 2, 'entertainment': 1, 'and': 3, 'pathology': 1, 'individuals': 1, 'presidency': 1, 'people': 2, 'success': 1, 'opulence': 1, 'excellence': 1, 'a': 1, 'president': 1, 'suits': 1, 'poverty': 1, 'white': 1, 'men': 1, 'suede': 1}

Let's get the word in each dictionary that has the biggest value.


In [80]:
most_follow_white = max(follows_white, key=follows_white.get)
most_follow_black = max(follows_black, key=follows_black.get)

In [81]:
print("The most used word that follows 'white' is: ",most_follow_white)
print("The most used word that follows 'black' is: ",most_follow_black)


The most used word that follows 'white' is:  house
The most used word that follows 'black' is:  and