数模心得(一)——Python进行JSON格式文件处理

最近参加了数学建模,在解题过程中有了一些心得,记录一下
非常渴望能得到python大大们的指点,非常感谢
Andrew_liu的博客对我的python学习有很大的帮助,在这里向他表示感谢

1. 文件处理步骤

  1. 利用Notepad++打开待处理文件,搜索到需要提取出的信息
  2. 分析信息在字典中的层次,采用合适方式进行提取,主要有两种情况:
    2.1 信息是字典中的一个序列,利用序列名直接在字典中进行提取
    2.2 信息是字典中某一序列的一部分,分析其特征设计正则表达式进行提取
  3. 去除其中的空数据和无效数据

注意字符的编码格式,我是统一用的utf-8格式
利用异常处理可以避免文件遍历时出现的中断
JSON的object对应python中的字典(dict),可以直接按照字典进行处理

2. 实现的功能

  1. 在所给的JSON文件中提取出以下信息:简历ID,性别,婚姻状况,学历,性别,预期职位,预计薪资
  2. 将所抽取的信息保存到另一个JSON文件中

3. 用到的python模块

  1. json模块:用于编码和解码JSON对象
  2. re模块:正则表达式模块

个人使用的python版本是3.5.1
re模块在python标准库中,直接导入就好
json模块需要利用pip安装

4. 源代码

输入文件每一行的开头都有'#RESUMEID#',利用strip()去除
输入文件有两个,为了避免覆盖,将写入文件'outputJsonFile'的打开方式设为'a+'
代码re.findall(r'"major":"(.*?)"', line, re.S)利用正则抽取专业信息
字符编码格式为'utf-8'

import re
import json

def processJson(inputJsonFile, outputJsonFile):
  fin = open(inputJsonFile, 'r', errors='ignore',  encoding='utf-8')
  fout = open(outputJsonFile, 'a+', errors='ignore', encoding='utf-8')
  
  for eachline in fin:
    line = eachline.strip()
    line = line.strip('#RESUMEID#')
    js = None
    majorStr = re.findall(r'"major":"(.*?)"', line, re.S)
    married = re.findall(r'"married":(.*?),', line, re.S)
    
  try:
        js = json.loads(line)
  except Exception as e:
        continue

  if ((js["expectPosition"]=='') or (js["expectPosition"]=='其他') or (js["address"]=='')
        or (js["expectSalary"]=='') or (js["expectSalary"]=='面议/月')):
        continue

  if (re.search(r'"expectSalary":"([0-9]*?)-', line, re.S)):
        js["expectSalary"] = re.findall(r'"expectSalary":"(.*?)-', line, re.S)
  else:
        continue

   jsout = {"ID":js["id"] , "address":js["address"],  'gender':js["gender"],  "degree":js["degree"], 
             "major":majorStr, "married": married,"expectPosition":js["expectPosition"],
             "expectSalary":js["expectSalary"]}
    outStr = json.dumps(jsout, ensure_ascii = False)

    fout.write(outStr)
    fout.write('\n')
    fin.close()
    fout.close()

if __name__ == '__main__':
processJson('201601.txt.json', 'Q1inputData.json')
processJson('201602.txt.json', 'Q1inputData.json')  

你可能感兴趣的:(数模心得(一)——Python进行JSON格式文件处理)