如何初始化对象与字典并将文件行数据映射至Article类?
实现步骤与代码示例
没问题,我来一步步帮你搞定这个需求~ 下面我会用两种常用语言给出完整方案,包含类定义、文件读取、对象初始化和字典存储的全流程:
方案一:C# 实现
1. 完善你的 Article 类
首先确保类的属性可赋值,还可以重写 ToString 方便直接打印对象内容:
public class Article { // 对应文件的三个参数 public int Code { get; set; } public string Name { get; set; } public string Amount { get; set; } // 重写ToString,便于快速查看对象信息 public override string ToString() { return $"Code: {Code}, Name: {Name}, Amount: {Amount}"; } }
2. 核心逻辑:读取文件、初始化对象与字典
这段代码会逐行处理文件,同时处理格式错误、重复Code等异常情况:
using System; using System.Collections.Generic; using System.IO; using System.Linq; class Program { static void Main() { // 初始化字典,用Code作为唯一键(假设Code不会重复) Dictionary<int, Article> articleDictionary = new Dictionary<int, Article>(); // 替换成你的实际文件路径 string filePath = @"C:\your_articles.txt"; try { // 逐行读取(大文件更高效,不会一次性加载全部内容) foreach (string line in File.ReadLines(filePath)) { // 跳过空行 if (string.IsNullOrWhiteSpace(line)) continue; // 清理行内容:去掉单引号、分割逗号、去除空格 string[] parts = line.Replace("'", "") .Split(',') .Select(part => part.Trim()) .ToArray(); // 检查格式是否符合要求 if (parts.Length != 3) { Console.WriteLine($"警告:行格式错误,已跳过:{line}"); continue; } // 尝试转换Code为整数 if (!int.TryParse(parts[0], out int code)) { Console.WriteLine($"警告:Code无法转换为整数,已跳过:{line}"); continue; } // 初始化Article对象并赋值 Article newArticle = new Article { Code = code, Name = parts[1], Amount = parts[2] }; // 添加到字典,避免重复Code if (!articleDictionary.ContainsKey(code)) { articleDictionary.Add(code, newArticle); Console.WriteLine($"已读取并添加:{newArticle}"); } else { Console.WriteLine($"警告:Code {code} 已存在,已跳过该行"); } } Console.WriteLine($"\n文件读取完成!字典中共有 {articleDictionary.Count} 个Article对象"); } catch (Exception ex) { Console.WriteLine($"读取文件出错:{ex.Message}"); } } }
方案二:Python 实现
1. 定义 Article 类
class Article: def __init__(self, code, name, amount): self.code = code self.name = name self.amount = amount # 重写__str__,方便打印对象 def __str__(self): return f"Code: {self.code}, Name: {self.name}, Amount: {self.amount}"
2. 核心读取逻辑
article_dict = {} file_path = "your_articles.txt" try: with open(file_path, 'r', encoding='utf-8') as file: for line_num, line in enumerate(file, 1): line = line.strip() # 跳过空行 if not line: continue # 清理行内容:去掉单引号、分割逗号、去除空格 parts = [part.strip().strip("'") for part in line.split(',')] # 检查格式 if len(parts) != 3: print(f"警告:第{line_num}行格式错误,已跳过:{line}") continue # 转换Code为整数 try: code = int(parts[0]) except ValueError: print(f"警告:第{line_num}行的Code不是有效整数,已跳过") continue # 创建对象并加入字典 new_article = Article(code, parts[1], parts[2]) if code not in article_dict: article_dict[code] = new_article print(f"已读取并添加:{new_article}") else: print(f"警告:第{line_num}行的Code {code} 已存在,已跳过") print(f"\n文件读取完成!字典中共有 {len(article_dict)} 个Article对象") except FileNotFoundError: print(f"错误:未找到文件 {file_path}") except Exception as e: print(f"读取文件出错:{str(e)}")
内容的提问来源于stack exchange,提问作者user7512602
相关产品推荐
相关产品推荐

