从文本文件提取元素并添加至字典的实现需求
处理文本生成指定格式字典的解决方案
没问题,这需求很清晰,咱们一步步来把文本内容转换成你要的两个字典。首先先理清楚原始文本的结构:每个用户的信息是name;password;friends的格式,只是输入的时候没换行,所以第一步得先把每个用户的记录拆分出来,再分别处理密码和好友部分。
实现代码(Python)
import re # 你的原始文本内容 raw_content = "john;9999;dave sam;8888; dave;7777;alex,john alex;6666;john,sam,dave" # 用正则匹配拆分出每个用户的完整记录 user_records = re.findall(r'([a-z]+;\d+;[a-z,]*)\s?', raw_content) # 初始化两个目标字典 dict1 = {} # 格式:{用户名: 密码(整数类型)} dict2 = {} # 格式:{用户名: 好友(空字符串/单个字符串/列表)} for record in user_records: # 拆分每个记录为用户名、密码、好友字段 name, password_str, friends_part = record.split(';') # 处理dict1:把密码转成整数存入 dict1[name] = int(password_str) # 处理dict2:根据好友字段的内容做不同处理 cleaned_friends = friends_part.strip() if not cleaned_friends: # 好友字段为空,存入空字符串 dict2[name] = '' elif ',' in cleaned_friends: # 多个好友,按逗号分割成列表 dict2[name] = cleaned_friends.split(',') else: # 单个好友,直接存入字符串 dict2[name] = cleaned_friends # 输出结果 print(dict1) print(dict2)
代码说明
- 拆分原始文本:用正则表达式
[a-z]+;\d+;[a-z,]*精准匹配每个用户的记录,避免直接按空格拆分可能出现的问题; - 处理密码字典(dict1):把密码字符串转换成整数,完全符合你期望的输出格式;
- 处理好友字典(dict2):区分三种情况:空字段存空字符串、单个好友存字符串、多个好友分割成列表,完美匹配你要的结果。
运行结果
{'john': 9999, 'sam': 8888, 'dave': 7777, 'alex': 6666} {'john': 'dave', 'sam': '', 'dave': ['alex', 'john'], 'alex': ['john', 'sam', 'dave']}
内容的提问来源于stack exchange,提问作者user14855804
相关产品推荐
相关产品推荐

