germany-2025-electoral-divergence / parse-germany-wiki.mjs
andrefelipe-afos
AFOS Germany 2025 Electoral Divergence — initial dataset
f843d84
Raw
History Blame Contribute Delete
8.47 kB
/**
* Parser determinístico das pesquisas da Wikipedia "Opinion polling for the 2025 German federal
* election". Materializa o grid (rowspan/colspan), mapeia colunas->PARTIDOS pelo cabeçalho.
* Sistema parlamentar: voto por PARTIDO, sem 2º turno. Molde Chile/Peru. Verifica contra o resultado.
*
* Entrada: ../../AFOS-Analitica-2026/.cache/germany-wiki.html
* Saída: polls/germany-polls.csv (long), polls/germany-polls.json
*/
import { readFileSync, writeFileSync, mkdirSync } from 'fs'
import { join } from 'path'
const HTML = readFileSync(join(process.cwd(), '..', '..', 'AFOS-Analitica-2026', '.cache', 'germany-wiki.html'), 'utf-8')
const OUT = join(process.cwd(), 'polls'); mkdirSync(OUT, { recursive: true })
const csv = (rows) => rows.map((r) => r.map((v) => { const s = String(v ?? ''); return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s }).join(',')).join('\n') + '\n'
// PARTIDO: token-do-cabeçalho -> {name (canônico p/ join c/ mercado), party}
const PARTY = {
'Grüne': { name: 'Grüne', party: 'Bündnis 90/Die Grünen' },
'Linke': { name: 'Die Linke', party: 'Die Linke' },
'Union': { name: 'CDU/CSU', party: 'Union (CDU/CSU)' },
'AfD': { name: 'AfD', party: 'AfD' },
'SPD': { name: 'SPD', party: 'SPD' },
'FDP': { name: 'FDP', party: 'FDP' },
'BSW': { name: 'BSW', party: 'Bündnis Sahra Wagenknecht' },
'FW': { name: 'Freie Wähler', party: 'Freie Wähler' },
}
const TOKENS = Object.keys(PARTY)
const decode = (s) => s
.replace(/<sup[^>]*class="[^"]*reference[^"]*"[^>]*>[\s\S]*?<\/sup>/gi, '')
.replace(/<style[\s\S]*?<\/style>/gi, '')
.replace(/<[^>]+>/g, '')
.replace(/&#(\d+);/g, (_, n) => String.fromCharCode(+n))
.replace(/&nbsp;/g, ' ').replace(/&ndash;/g, '–').replace(/&amp;/g, '&').replace(/&[a-z]+;/gi, ' ')
.replace(/ /g, ' ').replace(/\s+/g, ' ').trim()
function tables(html) { const out = []; const re = /<table[^>]*class="[^"]*wikitable[^"]*"[\s\S]*?<\/table>/gi; let m; while ((m = re.exec(html))) out.push(m[0]); return out }
function grid(tableHtml) {
const trs = tableHtml.split(/<tr[^>]*>/i).slice(1).map((x) => x.split(/<\/tr>/i)[0])
const g = []; const pending = []
for (const tr of trs) {
const cells = []; const cre = /<(t[hd])([^>]*)>([\s\S]*?)<\/\1>/gi; let cm
while ((cm = cre.exec(tr))) {
const attrs = cm[2]
const rs = parseInt((attrs.match(/rowspan="?(\d+)/i) || [])[1] || '1', 10)
const cs = parseInt((attrs.match(/colspan="?(\d+)/i) || [])[1] || '1', 10)
cells.push({ text: decode(cm[3]), rs, cs })
}
const row = []; let col = 0; let ci = 0
const place = (text) => { row[col] = text; col++ }
while (ci < cells.length || pending.some((p) => p.rows > 0)) {
const p = pending.find((x) => x.col === col && x.rows > 0)
if (p) { for (let k = 0; k < p.span; k++) place(p.text); p.rows--; continue }
if (ci >= cells.length) break
const c = cells[ci++]
for (let k = 0; k < c.cs; k++) { const cc = col; place(c.text); if (c.rs > 1) pending.push({ col: cc, span: 1, rows: c.rs - 1, text: c.text }) }
}
g.push(row)
}
return g
}
function labelColumns(g) {
const headerRows = g.slice(0, 4)
const ncol = Math.max(...g.map((r) => r.length))
const labels = []
for (let c = 0; c < ncol; c++) {
const texts = headerRows.map((r) => r[c] || '')
let label = null
for (const tk of TOKENS) if (texts.some((t) => t === tk || t.split(/[ /]/).includes(tk))) { label = `cand:${tk}`; break }
if (!label) {
const joined = texts.join(' ').toLowerCase()
if (/pollster|firm/.test(joined)) label = 'pollster'
else if (/sample/.test(joined)) label = 'sample'
else if (/margin/.test(joined)) label = 'margin'
else if (/fieldwork|date/.test(joined)) label = 'date'
else if (/other/.test(joined)) label = 'other'
else if (/abstention|lead/.test(joined)) label = 'skip'
}
labels.push(label)
}
return labels
}
const MONTHS = { jan: '01', feb: '02', mar: '03', apr: '04', may: '05', jun: '06', jul: '07', aug: '08', sep: '09', oct: '10', nov: '11', dec: '12' }
function endDate(s, fy) {
if (!s) return ''
const last = s.split(/[–-]/).pop().trim()
const ym = s.match(/([A-Za-z]{3})[a-z]*\s+(\d{4})/)
let day, mon, year
const mm = last.match(/(\d{1,2})\s+([A-Za-z]{3})[a-z]*\s+(\d{4})/)
if (mm) { day = mm[1]; mon = MONTHS[mm[2].toLowerCase()]; year = mm[3] }
else { const d = last.match(/(\d{1,2})/); const monM = last.match(/([A-Za-z]{3})/) || s.match(/([A-Za-z]{3})/); day = d ? d[1] : null; mon = monM ? MONTHS[monM[1].toLowerCase()] : null; year = ym ? ym[2] : fy }
if (!day || !mon || !year) return ''
return `${year}-${mon}-${String(day).padStart(2, '0')}`
}
const num = (s) => { const m = String(s).replace(/,/g, '').match(/-?\d+(?:\.\d+)?/); return m ? parseFloat(m[0]) : null }
const sampleNum = (s) => { const t = String(s || '').replace(/[.,\s]/g, ''); return /^\d+$/.test(t) ? parseInt(t, 10) : null }
const isData = (txt) => txt && !/^pollster|^firm|^date|^sample|^margin|^other|^abstention|^lead|results?$/i.test(txt) && txt.length > 1
const polls = []
const allTables = tables(HTML)
allTables.forEach((t, ti) => {
const g = grid(t)
const labels = labelColumns(g)
const candCols = labels.map((l, i) => ({ l, i })).filter((x) => x.l && x.l.startsWith('cand:'))
if (candCols.length < 4) return
const colOf = (name) => labels.indexOf(name)
const pc = colOf('pollster'), dc = colOf('date'), sc = colOf('sample')
if (pc < 0 || dc < 0) return
const yc = {}; for (const row of g) { const m = String(row[dc] || '').match(/\b(20\d\d)\b/); if (m) yc[m[1]] = (yc[m[1]] || 0) + 1 }
const tableYear = Object.keys(yc).sort((a, b) => yc[b] - yc[a])[0] || '2025'
let kept = 0
for (const row of g) {
const pollster = row[pc]
if (!isData(pollster)) continue
const date = row[dc]; const iso = endDate(date, tableYear)
if (!iso) continue
if (iso < '2024-01-01' || iso > '2025-02-23') continue
if (pollster.length > 40) continue
if (/election|result|\b(19|20)\d\d\b/.test(pollster)) continue
const sample = sc >= 0 ? sampleNum(row[sc]) : null
if (sample && sample > 200000) continue
const results = []
for (const { l, i } of candCols) { const tk = l.slice(5); const v = num(row[i]); if (v != null && v <= 100) results.push({ token: tk, candidate: PARTY[tk].name, party: PARTY[tk].party, percent: v }) }
if (results.length < 4) continue
if (results.every((r) => r.percent === results[0].percent)) continue
polls.push({ poll_date: iso, fieldwork: date, pollster: pollster.replace(/\s*\(.*/, '').trim(), sample, results })
kept++
}
if (kept > 0) console.error(` tabela #${ti}: ${candCols.length} partidos, ${kept} linhas`)
})
const m = new Map()
for (const p of polls) { const k = `${p.pollster}|${p.poll_date}`; const prev = m.get(k); if (!prev || p.results.length > prev.results.length) m.set(k, p) }
const POLLS = [...m.values()].sort((a, b) => a.poll_date.localeCompare(b.poll_date))
const rows = [['poll_date', 'fieldwork', 'pollster', 'sample', 'party', 'party_full', 'percent']]
for (const p of POLLS) for (const r of p.results) rows.push([p.poll_date, p.fieldwork, p.pollster, p.sample ?? '', r.candidate, r.party, r.percent])
writeFileSync(join(OUT, 'germany-polls.csv'), csv(rows))
writeFileSync(join(OUT, 'germany-polls.json'), JSON.stringify({
description: 'National opinion polls for the 2025 German federal election (Bundestag) — party vote share. Parliamentary system: one vote, no runoff. Parsed deterministically from the Wikipedia aggregation (rowspan/colspan-aware).',
source: 'Wikipedia "Opinion polling for the 2025 German federal election" (rendered table HTML)',
election: { date: '2025-02-23', type: 'Federal (Bundestag)', note: 'Snap election after the November 2024 coalition collapse.' },
counts: { polls: POLLS.length, rows: rows.length - 1 },
polls: POLLS,
}, null, 2))
console.log(`pesquisas: ${POLLS.length} (${rows.length - 1} linhas)`)
const parties = new Set(); for (const p of POLLS) for (const r of p.results) parties.add(r.candidate)
console.log(`partidos: ${parties.size} (${[...parties].join(', ')})`)
const last = POLLS.slice(-1)[0]
console.log(`CHECK pesquisa mais recente (esperado ~Union 28-29 / AfD 20-21 / SPD 15-16 / Grüne 12 / Linke 8): ${last ? last.poll_date + ' ' + last.pollster + ' ' + JSON.stringify(last.results.map((r) => [r.candidate, r.percent])) : 'n/a'}`)