Python技术求助:如何从两个TXT文件生成指定格式的输出?
解决方案
手动整理结果
直接匹配两个文件的对应信息,生成符合要求的格式内容:
- 约翰·多伊(门店经理)---- $750.00
- 简·多伊(门店副经理)---- $450.00
- 萨米·乔(值班经理)---- $350.00
自动化处理方法
如果需要批量处理这类文件,推荐以下两种实现方式:
1. Python 脚本
编写脚本读取两个文件,关联数据后输出指定格式:
# 读取薪资文件,构建姓名-薪资映射字典 salary_map = {} with open('salaries.txt', 'r', encoding='utf-8') as f: for line in f: line = line.strip() if not line: continue name, salary = line.rsplit(maxsplit=1) salary_map[name.strip()] = salary # 读取职位文件,匹配薪资并输出中文格式内容 position_cn_map = { '(Store Manager)': '(门店经理)', '(Asst Store Mngr)': '(门店副经理)', '(Shift Manager)': '(值班经理)' } with open('positions.txt', 'r', encoding='utf-8') as f: for line in f: line = line.strip() if not line: continue name, position = line.rsplit(maxsplit=1) name = name.strip() cn_position = position_cn_map.get(position, position) print(f"{name} {cn_position} ---- {salary_map.get(name, '未匹配到薪资')}")
2. Linux/Unix 命令行(awk)
使用awk命令快速关联两个文件的数据并输出:
BEGIN { # 定义职位中文映射 pos_cn["(Store Manager)"] = "(门店经理)" pos_cn["(Asst Store Mngr)"] = "(门店副经理)" pos_cn["(Shift Manager)"] = "(值班经理)" FS = "[[:space:]]+" } # 先读取薪资文件,存入字典 NR == FNR { salary[$1 " " $2] = $3 next } # 处理职位文件,匹配输出 { full_name = $1 " " $2 chinese_pos = pos_cn[$3] ? pos_cn[$3] : $3 printf "%s %s ---- %s\n", full_name, chinese_pos, salary[full_name] }
执行命令:awk -f merge_data.awk salaries.txt positions.txt
内容的提问来源于stack exchange,提问作者GoBucks_CHS
相关产品推荐
相关产品推荐

