Created
February 3, 2026 03:14
-
-
Save kujirahand/9b57f10821d436d60e7371f4cdd5f2db to your computer and use it in GitHub Desktop.
住所で郵便番号データをソート
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
| use std::fs::File; | |
| use std::io::{BufRead, BufReader}; | |
| use std::error::Error; | |
| fn main() -> Result<(), Box<dyn Error>> { | |
| // 対象CSVファイルを開いてバッファ付きリーダーで巻き取る --- (*1) | |
| let file = File::open("utf_ken_all.csv")?; | |
| let reader = BufReader::new(file); | |
| // 住所カナや郵便番号・住所を一時保存する構造体を蓄積 --- (*2) | |
| let mut entries = Vec::new(); | |
| // 1行ずつ読み込んでCSVフィールドを抽出 --- (*3) | |
| for line in reader.lines() { | |
| let line = line?; | |
| if line.is_empty() { | |
| continue; | |
| } | |
| // フィールドを分割してトリムし、必要な情報を抽出 --- (*4) | |
| let fields: Vec<String> = line | |
| .split(',') | |
| .map(|s| s.trim_matches('"').to_string()) | |
| .collect(); | |
| // 住所カタカナ(5列目と6列目)、郵便番号(3列目)、住所(8列目と9列目)を取得 --- (*5) | |
| let kana_key = format!("{}{}", fields.get(4).map(String::as_str).unwrap_or(""), fields.get(5).map(String::as_str).unwrap_or("")); | |
| let postal = fields.get(2).map(String::as_str).unwrap_or("").to_string(); | |
| let address = format!("{}{}", fields.get(7).map(String::as_str).unwrap_or(""), fields.get(8).map(String::as_str).unwrap_or("")); | |
| // 抽出した情報をタプルとしてベクタに追加 --- (*6) | |
| entries.push((kana_key, postal, address)); | |
| } | |
| // 住所カナをキーに昇順ソートし、先頭5件を出力 --- (*7) | |
| entries.sort_by(|a, b| a.0.cmp(&b.0)); | |
| for (_, postal, address) in entries.iter().take(5) { | |
| println!("{} {}", postal, address); | |
| } | |
| Ok(()) | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
メモリ使用量に配慮したプログラム