如何用JavaScript对文本文件中的城市人口按指定区间分组并处理空白值?
别慌,我来一步步帮你搞定这个城市人口分组的需求!先提一句,你写的区间看起来有点笔误(比如<5000且>7499这种逻辑矛盾),我默认按合理的区间来实现:<5000、5000-7499、7500-9999、≥10000,空白人口标记为NA。下面是完整的实现方案:
实现步骤说明
1. 读取文本文件
首先得把文本文件里的内容读出来,浏览器和Node.js环境的实现方式略有不同,我都给你列出来:
浏览器端(网页中读取本地文件)
假设你页面上有一个文件选择按钮:<input type="file" id="fileInput">,用下面的代码监听文件选择事件并读取内容:
const fileInput = document.getElementById('fileInput'); fileInput.addEventListener('change', (e) => { const selectedFile = e.target.files[0]; if (!selectedFile) return; const reader = new FileReader(); reader.onload = (event) => { const textContent = event.target.result; // 拿到文本后开始处理数据 processCityPopulationData(textContent); }; reader.readAsText(selectedFile); });
Node.js端(服务器/本地脚本读取文件)
用Node.js内置的fs模块读取文件:
const fs = require('fs'); const path = require('path'); // 替换成你的文本文件路径 const filePath = path.resolve(__dirname, 'city-populations.txt'); fs.readFile(filePath, 'utf8', (err, textContent) => { if (err) { console.error('读取文件出错啦:', err); return; } processCityPopulationData(textContent); });
2. 解析文本提取城市和人口数据
你的示例数据格式是[城市名] city [人口数],用正则表达式可以轻松匹配提取。同时处理空白或无效的人口记录,标记为NA:
function processCityPopulationData(text) { // 按行分割文本,过滤掉空行 const lines = text.split('\n').filter(line => line.trim() !== ''); const cityList = lines.map(line => { // 正则匹配城市名称和人口(兼容带逗号的千位分隔符) const matchResult = line.match(/^(.*?)\s+city\s+([\d,]*)$/); // 匹配失败的情况,直接标记人口为NA if (!matchResult) { return { cityName: line.trim(), population: 'NA' }; } const cityName = matchResult[1].trim(); const populationStr = matchResult[2].trim(); // 处理空白人口或非数字的情况 if (!populationStr || isNaN(parseInt(populationStr.replace(/,/g, '')))) { return { cityName, population: 'NA' }; } // 去掉逗号,转换为数字类型 const population = parseInt(populationStr.replace(/,/g, ''), 10); return { cityName, population }; }); // 解析完成后开始分组 groupCitiesByPopulation(cityList); }
3. 按人口区间分组
按照我们约定的区间分组,你可以根据实际需求修改判断条件:
function groupCitiesByPopulation(cityList) { // 初始化分组容器 const populationGroups = { 'NA': [], '<5000': [], '5000-7499': [], '7500-9999': [], '≥10000': [] }; cityList.forEach(cityItem => { if (cityItem.population === 'NA') { populationGroups['NA'].push(cityItem.cityName); } else if (cityItem.population < 5000) { populationGroups['<5000'].push(cityItem.cityName); } else if (cityItem.population >= 5000 && cityItem.population <= 7499) { populationGroups['5000-7499'].push(cityItem.cityName); } else if (cityItem.population >= 7500 && cityItem.population <= 9999) { populationGroups['7500-9999'].push(cityItem.cityName); } else { populationGroups['≥10000'].push(cityItem.cityName); } }); // 生成最终报告 generatePopulationReport(populationGroups); }
4. 生成分组报告
可以把报告输出到控制台,或者在网页上展示:
function generatePopulationReport(groups) { console.log('=== 城市人口分组报告 ==='); Object.entries(groups).forEach(([groupName, cities]) => { console.log(`\n${groupName}:`); if (cities.length === 0) { console.log(' 暂无数据'); } else { cities.forEach(city => console.log(` - ${city}`)); } }); // 如果是浏览器端,也可以把报告插入到页面元素中 // const reportContainer = document.getElementById('report-container'); // let reportHtml = '<h2>城市人口分组报告</h2>'; // Object.entries(groups).forEach(([groupName, cities]) => { // reportHtml += `<h3>${groupName}</h3>`; // reportHtml += '<ul>'; // cities.forEach(city => reportHtml += `<li>${city}</li>`); // reportHtml += '</ul>'; // }); // reportContainer.innerHTML = reportHtml; }
注意事项
- 如果你的文本格式和示例有差异(比如城市名里包含“city”),需要调整正则表达式的匹配规则
- 人口数的千位分隔符处理很重要,一定要先去掉逗号再转换为数字
- 如果你实际需要的区间和我假设的不一样,直接修改
groupCitiesByPopulation里的判断条件就行
内容的提问来源于stack exchange,提问作者tvalentine
相关产品推荐
相关产品推荐

