NYC Data Science Academy| Blog
Bootcamps
Lifetime Job Support Available Financing Available
Bootcamps
Data Science with Machine Learning Flagship 🏆 Data Analytics Bootcamp
Free Lesson
Intro to Data Science New Release 🎉
Find Inspiration
Find Alumni with Similar Background
Job Outlook
Occupational Outlook Graduate Outcomes Must See 🔥
Alumni
Success Stories Testimonials Alumni Directory Alumni Exclusive Study Program
Courses
View Bundled Courses
Financing Available
Bootcamp Prep Popular 🔥 Data Science Mastery Data Science Launchpad with Python View AI Courses Generative AI for Everyone New 🎉 Generative AI for Finance New 🎉 Generative AI for Marketing New 🎉
Bundle Up
Learn More and Save More
Combination of data science courses.
View Data Science Courses
Beginner
Introductory Python
Intermediate
Data Science Python: Data Analysis and Visualization Popular 🔥 Data Science R: Data Analysis and Visualization
Advanced
Data Science Python: Machine Learning Popular 🔥 Data Science R: Machine Learning Designing and Implementing Production MLOps New 🎉 Natural Language Processing for Production (NLP) New 🎉
Find Inspiration
Get Course Recommendation Must Try 💎 An Ultimate Guide to Become a Data Scientist
For Companies
For Companies
Corporate Offerings Hiring Partners Candidate Portfolio Hire Our Graduates
Students Work
Students Work
All Posts Capstone Data Visualization Machine Learning Python Projects R Projects
Tutorials
About
About
About Us Accreditation Contact Us Join Us FAQ Webinars Subscription An Ultimate Guide to
Become a Data Scientist
    Login
NYC Data Science Acedemy
Bootcamps
Courses
Students Work
About
Bootcamps
Bootcamps
Data Science with Machine Learning Flagship
Data Analytics Bootcamp
Free Lessons
Intro to Data Science New Release 🎉
Find Inspiration
Find Alumni with Similar Background
Job Outlook
Occupational Outlook
Graduate Outcomes Must See 🔥
Alumni
Success Stories
Testimonials
Alumni Directory
Alumni Exclusive Study Program
Courses
Bundles
financing available
View All Bundles
Bootcamp Prep
Data Science Mastery
Data Science Launchpad with Python NEW!
View AI Courses
Generative AI for Everyone
Generative AI for Finance
Generative AI for Marketing
View Data Science Courses
View All Professional Development Courses
Beginner
Introductory Python
Intermediate
Python: Data Analysis and Visualization
R: Data Analysis and Visualization
Advanced
Python: Machine Learning
R: Machine Learning
Designing and Implementing Production MLOps
Natural Language Processing for Production (NLP)
For Companies
Corporate Offerings
Hiring Partners
Candidate Portfolio
Hire Our Graduates
Students Work
All Posts
Capstone
Data Visualization
Machine Learning
Python Projects
R Projects
About
Accreditation
About Us
Contact Us
Join Us
FAQ
Webinars
Subscription
An Ultimate Guide to Become a Data Scientist
Tutorials
Data Analytics
  • Learn Pandas
  • Learn NumPy
  • Learn SciPy
  • Learn Matplotlib
Machine Learning
  • Boosting
  • Random Forest
  • Linear Regression
  • Decision Tree
  • PCA
Interview by Companies
  • JPMC
  • Google
  • Facebook
Artificial Intelligence
  • Learn Generative AI
  • Learn ChatGPT-3.5
  • Learn ChatGPT-4
  • Learn Google Bard
Coding
  • Learn Python
  • Learn SQL
  • Learn MySQL
  • Learn NoSQL
  • Learn PySpark
  • Learn PyTorch
Interview Questions
  • Python Hard
  • R Easy
  • R Hard
  • SQL Easy
  • SQL Hard
  • Python Easy
Data Science Blog > Student Works > Scraping the Partisan Divide: Sentiment, Text, & Network Analysis of an online political discussion forum using Python.

Scraping the Partisan Divide: Sentiment, Text, & Network Analysis of an online political discussion forum using Python.

Franklin Dickinson
Posted on May 30, 2018

In this post I apply data science techniques to investigate partisan division on scraped user post data from the online political discussion forum Liberalforum.net.

 

My process:

  1.  Scrape Text and user partisan identity and text for each post.
  2. Consolidate Partisanship from all partisan identities into a general 'liberal' and 'conservative' buckets.
  3. Distinguish Top Phrases for each bucket.
  4. Analyze Sentiment between partisan identities on posts matching political keywords.
  5. Identify Communities via network analysis to investigate partisan division.

Demonstrated Python Skills:

  • Web-scraping with Scrapy
  • Text Analysis with NLTK and Sklearn.CountVectorizer
  • Sentiment Analysis with TextBlob
  • Network Analysis with NetworkX and Community
  • Visualization with Seaborrn

Check out my Github gists for both my scraping and analyses.


The Data

I chose to web-scrape this online political discussion specifically because:

  • Social-based text data - apply NLP & Sentiment Analysis
  • Website data not available via API
  • A high percentage of of users self-identify their partisan identity, an interesting factor for analysis.

I must additionally be careful to not fully extrapolate the results gleamed from these heavy forum users to the general public.


Web-Scraping

I performed my scraping using the open source Python package Scrapy identifying and pulling text via html tags.

  • # of Posts:  249,749
  • Date Range: 1/1/16 -  5/12/18

Structure of the scraped data:

Defined # of Threads -> X Pages per Thread -> X Posts per Page

My Scrapy spider crawls through each thread chronology,  identifies the total # of posts per thread, and crawls through each post of page.

Scraped data includes:

  • post date and text
  • thread title and first poster
  • user name, total number of posts, and political ideology

 


Political Ideology

Of the 253 users who posted on the forum, 129 (51%) self-identified politically, who accounted for 62% of the total posts.


 

I next consolidated these ideologies with n > 5 along the conventional liberal to conservative US ideological spectrum,  discluding 'independents'.

 

Conservative Liberal
Conservative; Republican;

Libertarian; Capitalist

Liberal; Progressive; Socialist;

Democratic; Anarchist; Green

 


Interestingly enough, despite equal numbers of liberal and conservative users, on Liberalforum.net, conservative users author a large majority of posts.


Top Words

Using the CountVectorizer package from sklearn.feature_extraction.text, I created a 2 n-gram corpus of phrases from the NLP=processed user-post text data.

I split the data between liberal and conservative users, and sorted the output to gain the top 20 2-word phrases for each group.


Findings:

  • Politicians
    • Conservatives had a higher count of 'hilary clinton' than 'donald trump  and Liberals vice versa.
      • This supports the idea that users more frequently discuss topics they are disparaging.
  • Policy topics
    • Much more frequent in Liberals top list than Conservative top list.
      • Conservatives - 'tax cut',
      • Liberals - 'tax cut',  'health care', 'wall street', 'foreign polici',
  • 'Gibberish Nonsense'
    • Emotive or sarcastic phrases expressing style of users
    • Indicates higher sophistication of sentiment analysis necessary down the line.

Analyzing Sentiment

Using the Python package TextBlob, I  ran a sentiment analysis on the text of each of the  250k+ scraped posts.

I first applied standard NLP cleaning to the postText data, removing stopwords and stemming the text. I then fed the simplified outputs into the TextBlob sentiment analyzer.

The analyzer works via Naive Bayes classification, built upon the Stanford NLTK program.

TextBlob's sentiment analysis outputs two scores:

  • Subjectivity
    •  0  (highly objective) to 1 (highly subjective)
  • Polarity
    •  -1 (highly negative attitude) to +1 (highly positive attitude)

Political Conversations

I next look to identify partisan differences in sentiment regarding known polarized political keywords. .

For each keyword, I segmented out all containing posts along with the # of identifying users.

 

keywords # posts # users - liberal  # users - conservative
'trump'
13,731
 25 28
'hilary'; 'clinton'
3,425
 18 22
'obama 2,454  24 15
'russia' 1,240 11 18

 

Since the posts/user distribution is so skewed, I chose as the unit of study the distribution of mean sentiment values of each user.

This prevents the scores of a few high posting users from flooding out other users and thus keeps the analysis focused on the conversation occurring between users. 

Subjectivity and Polarity box-plot distributions for each political keyword:





Findings:
  •  Subjectivity
    • Each side tends to have lower subjectivity toward political keywords they support, and higher subjectivity toward political keywords they oppose.
      • Possibly users are being more emotional in railing against other side, while being more rational in defending their own side
    • The "Russia" keyword has the largest difference between the two views.
      • Does lower subjectivity ratings among liberals suggest they structuring their arguments more objectivity than conservatives? What does this signify?
  • Polarity
    • Each side is more more positive toward political figures they support!
    • On 'Russia', Conservatives have a higher mean and larger distribution than Liberals
    • Across all keywords, means are centered around 0.
      • Further Work: Limit text analyzed to single sentence containing keyword rather than the entire post.

Social Network Analysis

To what extent are political discussions on the forum crossing the ideological divide?

To find out, I implemented a network analysis via the Python package NetworkX.

A network analysis is made up of nodes, in this cases users, linked by edges, in this case posting on another user's thread..

I color my nodes via the partisan identification of the users (grey = not segmented):

The network visually consists of:

  • one main cluster
    • inner core layer - users all highly connected to one-another
    • outer layer - users connected to one or a few users in the inner region
  • a second minuscule cluster of 3 users connected together via only one user.

Next, I used the best_partition() function of the communities package to partition the nodes into the groupings which maximizes the modularity, the ratio of the connection density within each groups relative to the connection density between groups, using the Louvain heuristics. I also weighted the partition via the total number of posts by each user. In this case we are returned 5 segments.

Now to  resolve my question, I analyze the makeup of each of these 5 segments:

With the caveat that partisan identity data is available for only about half of all users, analyzing the breakdown among those users (the difference in count between 'LeftRight_binary' and 'conservative_binary' for each row) shows that the communities within the main cluster are all considerably balanced between conservative and liberal users.

Thus, there is evidence that users are socializing across the partisan divide and the forum is serving as a space for political debate.


Future Work

  1.  Build out more sophisticated NLP tagging and sentiment analysis: entities, key phrases and multi-dimensional sentiment score. 
  2.  Create a Naive Bayes classifier to predict whether posts were written by a  'Liberal' or 'Conservative'  user based on their text.

 

Check out my code for this project via my Jupyter notebook Gist on Github.

About Author

Franklin Dickinson

Business Strategist. Creative Technologist. Critical Thinker. Current fellow at NYC Data Science Academy, utilizing R, Python, machine learning, and big data to test intuitions and drive insights.
View all posts by Franklin Dickinson >

Leave a Comment

Cancel reply

You must be logged in to post a comment.

May Data Analytics News, my selection! – DataMathStat May 31, 2018
[…] Analyzing sentiment of an online political discussion forum: Using the Python package Scrapy for scrapping and the Python package TextBlob for sentiment analysis. […]

View Posts by Categories

All Posts 2326 posts
Alumni 60 posts
APIs 40 posts
AWS 11 posts
Big Data 48 posts
Capstone 196 posts
Career Education 7 posts
Community 70 posts
Data Engineering 1 posts
Data Science News and Sharing 71 posts
Data Visualization 312 posts
Events 5 posts
Featured 37 posts
Hadoop 13 posts
Machine Learning 336 posts
Meetup 142 posts
Python 435 posts
R 395 posts
R Shiny 548 posts
R Visualization 440 posts
Spark 17 posts
Student Works 1610 posts
Tableau 12 posts
TensorFlow 2 posts
Web Scraping 480 posts

Our Recent Popular Posts

AI 4 AI: ChatGPT Unifies My Blog Posts
by Vinod Chugani
Dec 18, 2022
Meet Your Machine Learning Mentors: Kyle Gallatin
by Vivian Zhang
Nov 4, 2020
NICU Admissions and CCHD: Predicting Based on Data Analysis
by Paul Lee, Aron Berke, Bee Kim, Bettina Meier and Ira Villar
Jan 7, 2020

View Posts by Tags

#python #trainwithnycdsa 2019 2020 Revenue 3-points agriculture air quality airbnb airline alcohol Alex Baransky algorithm alumni Alumni Interview Alumni Reviews Alumni Spotlight alumni story Alumnus ames dataset ames housing dataset apartment rent API Application artist aws bank loans beautiful soup Best Bootcamp Best Data Science 2019 Best Data Science Bootcamp Best Data Science Bootcamp 2020 Best Ranked Big Data Book Launch Book-Signing bootcamp Bootcamp Alumni Bootcamp Prep boston safety Bundles cake recipe California Cancer Research capstone car price Career Career Day citibike classic cars classpass clustering Coding Course Demo Course Report covid 19 credit credit card crime frequency crops D3.js data data analysis Data Analyst data analytics data for tripadvisor reviews data science Data Science Academy Data Science Bootcamp Data science jobs Data Science Reviews Data Scientist Data Scientist Jobs data visualization database Deep Learning Demo Day Discount disney dplyr drug data e-commerce economy employee employee burnout employer networking environment feature engineering Finance Financial Data Science fitness studio Flask flight delay gbm Get Hired ggplot2 googleVis H20 Hadoop hallmark holiday movie happiness healthcare frauds higgs boson Hiring hiring partner events Hiring Partners hotels housing housing data housing predictions housing price hy-vee Income Industry Experts Injuries Instructor Blog Instructor Interview insurance italki Job Job Placement Jobs Jon Krohn JP Morgan Chase Kaggle Kickstarter las vegas airport lasso regression Lead Data Scienctist Lead Data Scientist leaflet league linear regression Logistic Regression machine learning Maps market matplotlib Medical Research Meet the team meetup methal health miami beach movie music Napoli NBA netflix Networking neural network Neural networks New Courses NHL nlp NYC NYC Data Science nyc data science academy NYC Open Data nyc property NYCDSA NYCDSA Alumni Online Online Bootcamp Online Training Open Data painter pandas Part-time performance phoenix pollutants Portfolio Development precision measurement prediction Prework Programming public safety PwC python Python Data Analysis python machine learning python scrapy python web scraping python webscraping Python Workshop R R Data Analysis R language R Programming R Shiny r studio R Visualization R Workshop R-bloggers random forest Ranking recommendation recommendation system regression Remote remote data science bootcamp Scrapy scrapy visualization seaborn seafood type Selenium sentiment analysis sentiment classification Shiny Shiny Dashboard Spark Special Special Summer Sports statistics streaming Student Interview Student Showcase SVM Switchup Tableau teachers team team performance TensorFlow Testimonial tf-idf Top Data Science Bootcamp Top manufacturing companies Transfers tweets twitter videos visualization wallstreet wallstreetbets web scraping Weekend Course What to expect whiskey whiskeyadvocate wildfire word cloud word2vec XGBoost yelp youtube trending ZORI

NYC Data Science Academy

NYC Data Science Academy teaches data science, trains companies and their employees to better profit from data, excels at big data project consulting, and connects trained Data Scientists to our industry.

NYC Data Science Academy is licensed by New York State Education Department.

Get detailed curriculum information about our
amazing bootcamp!

Please enter a valid email address
Sign up completed. Thank you!

Offerings

  • HOME
  • DATA SCIENCE BOOTCAMP
  • ONLINE DATA SCIENCE BOOTCAMP
  • Professional Development Courses
  • CORPORATE OFFERINGS
  • HIRING PARTNERS
  • About

  • About Us
  • Alumni
  • Blog
  • FAQ
  • Contact Us
  • Refund Policy
  • Join Us
  • SOCIAL MEDIA

    © 2023 NYC Data Science Academy
    All rights reserved. | Site Map
    Privacy Policy | Terms of Service
    Bootcamp Application