uk-2024-electoral-divergence / parse-uk-wiki.mjs
andrefelipe-afos
AFOS UK 2024 Electoral Divergence dataset (prediction market vs polls)
85f3060
Raw
History Blame Contribute Delete
9.72 kB
/**
* Parser determinístico das pesquisas da Wikipedia "Opinion polling for the 2024 United Kingdom
* general election". Voto por PARTIDO (Lab/Con/LD/Ref/Grn/SNP/PC), sistema FPTP, sem 2º turno.
* Molde Canadá/Alemanha. Verifica contra o resultado (Labour venceu mais cadeiras: 411 seats, 33.7%).
*
* Entrada: ../../AFOS-Analitica-2026/.cache/uk-wiki.html
* Saída: polls/uk-polls.csv (long), polls/uk-polls.json
*/
import { readFileSync, writeFileSync, mkdirSync } from 'fs'
import { join } from 'path'
const HTML = readFileSync(join(process.cwd(), '..', '..', 'AFOS-Analitica-2026', '.cache', 'uk-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'
// Tokens = exatamente os cabeçalhos de coluna da Wikipedia UK (Con|Lab|LD|SNP|Grn|Ref|PC)
const PARTY = {
'Lab': { name: 'Labour', party: 'Labour Party' },
'Con': { name: 'Conservative', party: 'Conservative Party' },
'LD': { name: 'Lib Dems', party: 'Liberal Democrats' },
'Ref': { name: 'Reform', party: 'Reform UK' },
'Grn': { name: 'Green', party: 'Green Party' },
'SNP': { name: 'SNP', party: 'Scottish National Party' },
'PC': { name: 'Plaid Cymru', party: 'Plaid Cymru' },
}
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 a = cm[2]; const rs = parseInt((a.match(/rowspan="?(\d+)/i) || [])[1] || '1', 10); const cs = parseInt((a.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 = (t) => { row[col] = t; 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 j = texts.join(' ').toLowerCase()
if (/pollster|firm/.test(j)) label = 'pollster'
else if (/sample/.test(j)) label = 'sample'
else if (/margin|lead/.test(j)) label = 'margin'
else if (/date/.test(j)) label = 'date'
else if (/other/.test(j)) label = 'other' }
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|^link|^lead|results?$/i.test(txt) && txt.length > 1
// janela do ciclo: ano eleitoral 2024 até o dia da eleição
const FLOOR = '2024-01-01', CEIL = '2024-07-04'
// A página cobre vários anos (2019+) e tem tabelas regionais/hipotéticas. A tabela nacional de 2024 é a
// MAIOR tabela canônica com 2024 EXPLÍCITO. Anos anteriores (2023/2022/2021) não trazem o ano nas células
// e cairiam no default — por isso exigimos 2024 explícito (senão poluem a janela com valores de outro ano).
const tableData = []
tables(HTML).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 < 6) return // a nacional tem 7 partidos
const toks = candCols.map((c) => c.l); if (new Set(toks).size !== toks.length) return // layout torto (token de partido duplicado)
const colOf = (n) => labels.indexOf(n); 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 }
if (!yc['2024']) return // exigir 2024 EXPLÍCITO (evita anos anteriores remapeados)
const tableYear = '2024'
const tpolls = []
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 < FLOOR || iso > CEIL) 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
if (results.some((r) => r.percent > 55)) continue // plausibilidade: nenhum partido nacional UK 2024 passou de ~46%
tpolls.push({ poll_date: iso, fieldwork: date, pollster: pollster.replace(/\s*\(.*/, '').trim(), sample, results })
}
if (tpolls.length) tableData.push({ ti, n: tpolls.length, polls: tpolls })
if (process.env.DIAG) console.error('TI', ti, '2024 canônica:', tpolls.length, 'linhas')
})
tableData.sort((a, b) => b.n - a.n)
const polls = tableData.length ? tableData[0].polls : []
if (tableData.length) console.error(`tabela nacional = TI ${tableData[0].ti} (${polls.length} linhas); descartadas: ${tableData.slice(1).map((x) => `TI${x.ti}(${x.n})`).join(', ') || 'nenhuma'}`)
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, 'uk-polls.csv'), csv(rows))
writeFileSync(join(OUT, 'uk-polls.json'), JSON.stringify({
description: 'National opinion polls for the 2024 United Kingdom general election — party vote share. FPTP parliamentary system: one vote, no runoff; the prediction market prices which party wins the most seats. Parsed deterministically from the Wikipedia aggregation (rowspan/colspan-aware).',
source: 'Wikipedia "Opinion polling for the 2024 United Kingdom general election" (rendered table HTML)',
election: { date: '2024-07-04', type: 'General (House of Commons)', note: 'Labour (Starmer) won a landslide of seats (411) on 33.7% of the vote; the Conservatives (Sunak) collapsed and Reform UK took 14.3% of the vote but only 5 seats.' },
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(', ')})`)
console.log(`range: ${POLLS[0]?.poll_date} -> ${POLLS.slice(-1)[0]?.poll_date}`)
const last = POLLS.slice(-1)[0]
console.log(`CHECK pesquisa mais recente (esperado ~Labour 38-41 / Conservative 20-23 / Reform 14-17 / LD 10-12): ${last ? last.poll_date + ' ' + last.pollster + ' ' + JSON.stringify(last.results.map((r) => [r.candidate, r.percent])) : 'n/a'}`)