Last active
August 21, 2021 12:11
-
-
Save lucahammer/21cc65be6897f6fccea7de4e4fa95910 to your computer and use it in GitHub Desktop.
Python script to create a Gephi network from voteswiper.org data
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
Copyright 2021 Luca Hammer | |
Permission is hereby granted, free of charge, to any person obtaining a copy of | |
this software and associated documentation files (the "Software"), to deal in the | |
Software without restriction, including without limitation the rights to use, copy, | |
modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, | |
and to permit persons to whom the Software is furnished to do so, subject to the | |
following conditions: | |
The above copyright notice and this permission notice shall be included in all | |
copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, | |
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A | |
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT | |
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF | |
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE | |
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | |
''' | |
import requests | |
from bs4 import BeautifulSoup | |
import json | |
r = requests.get('https://www.voteswiper.org/germany/federal-election-2021') | |
soup = BeautifulSoup(r.content) | |
data = json.loads(soup.find('script', type='application/json').string)['props']['pageProps'] | |
parties = [] | |
for party in data['parties']: | |
overlaps = [] | |
for party_target in data['parties']: | |
overlap = 0 | |
for i, answers_source in enumerate(party['pivot']['answers']): | |
if answers_source['answer'] == party_target['pivot']['answers'][i]['answer']: | |
overlap += 1 | |
overlaps.append({'name' : party_target['name'], | |
'overlap' : overlap}) | |
parties.append({ | |
'name' : party['name'], | |
'overlaps' : overlaps | |
}) | |
# be sure to choose "merge strategy first" when opening the file in Gephi because | |
# each combination appears twice | |
with open ('2021-08-21-voteswiper_partyoverlaps_federal.gdf', 'w') as f: | |
f.write('nodedef>name VARCHAR,label VARCHAR\n') | |
f.write('edgedef>node1 VARCHAR,node2 VARCHAR, weight DOUBLE\n') | |
for party in parties: | |
for overlap in party['overlaps']: | |
if party['name'] is not overlap['name']: | |
f.write(f"{party['name']},{overlap['name']},{overlap['overlap']}\n") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment