博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python基础:输入与输出(I/O)
阅读量:4630 次
发布时间:2019-06-09

本文共 3128 字,大约阅读时间需要 10 分钟。

来做一个NLP任务

  步骤为:
    1.读取文件;
    2.去除所有标点符号和换行符,并把所有大写变成小写;
    3.合并相同的词,统计每个词出现的频率,并按照词频从大到小排序;
    4.将结果按行输出到文件 out.txt。
  代码:
import reimport os,sys# 你不用太关心这个函数def parse(text):  # 使用正则表达式去除标点符号和换行符  text = re.sub(r'[^\w ]', '', text)  # 转为小写  text = text.lower()  # 生成所有单词的列表  word_list = text.split(' ')  # 去除空白单词  word_list = filter(None, word_list)  # 生成单词和词频的字典  word_cnt = {}  for word in word_list:    if word not in word_cnt:      word_cnt[word] = 0      word_cnt[word] += 1      print(word_cnt.items())  # 按照词频排序  sorted_word_cnt = sorted(word_cnt.items(), key=lambda kv: kv[1], reverse=True)  return sorted_word_cntinFile = 'in.txt'if not os.path.exists(inFile):  print(f'file {inFile} not exist')  sys.exit()with open(inFile, 'r') as fin:  text = fin.read()word_and_freq = parse(text)outFile = 'out.txt'with open(outFile, 'w') as fout:  for word, freq in word_and_freq:    try:      fout.write('{} {}\n'.format(word, freq))    except Exception as ex:      print(f"error in wirte {outFile},error msg:{ex}")
  假如文件非常大,一次性读取可能会导致内存崩溃,那么可以用一行一行读取的方法来实现:
from collections import defaultdictimport re,sys,osinFile = 'in.txt'if not os.path.exists(inFile):  print(f'file {inFile} not exist')  sys.exit()f = open(inFile, mode="r", encoding="utf-8")word_cnt = defaultdict(int) #defaultdict类的初始化函数接受一个类型作为参数,当所访问的键不存在的时候,可以实例化一个值作为默认值for line in f: #逐行读取  line =re.sub(r'[^\w ]', '', line) #使用正则表达式去除标点符号和换行符  for word in filter(None, line.split(' ')): #按空格把单词分组,并把空白单词去掉    word_cnt[word] += 1outFile = 'out.txt'with open(outFile,'w') as fout:  for word, freq in sorted(word_cnt.items(), key=lambda kv: kv[1], reverse=True):    try:      fout.write(f'{word} {freq}\n')    except Exception as ex:      print(f"error in wirte {outFile},error msg:{ex}")

  I/O需谨慎,所有I/O操作都应该进行错误处理,以防编码漏洞。

Json 序列化与反序列化

  json.dumps() 这个函数,接受 Python 的基本数据类型,然后将其序列化为 string;

  json.loads() 这个函数,接受一个合法字符串,然后将其反序列化为 Python 的基本数据类型。

  同样的,Json序列化与反序列化时也要注意做错误处理,比如json.loads('123.2')会返回一个float类型。因此反序列化后需要判断是否期望的类型:
original_params = json.loads(params_str)t = type(original_params)if t is not dict:    print(f'is {t} not dict')

  json.dumps() 与json.loads()例子:

import json,sysparams = {'symbol': '123456','type': 'limit','price': 123.4,'amount': 23}try:    params_str = json.dumps(params)except Exception as ex:    print(f'error on dumps error msg:{ex}')    sys.exit()print('after json serialization') print('type of params_str = {}, params_str = {}'.format(type(params_str), params)) #after json serialization#type of params_str = 
, params_str = {'symbol': '123456', 'type': 'limit', 'price': 123.4, 'amount': 23}original_params = json.loads(params_str)t = type(original_params)if t is not dict: print(f'is {t} not dict')print('after json deserialization')print('type of original_params = {}, original_params = {}'.format(type(original_params), original_params))#after json deserialization #type of original_params =
, original_params = {'symbol': '123456', 'type': 'limit', 'price': 123.4, 'amount': 23}

 

 

参考资料:

极客时间《Python核心技术与实战》

转载于:https://www.cnblogs.com/xiaoguanqiu/p/10914987.html

你可能感兴趣的文章
vs2010统计项目代码总行数
查看>>
delphi 一个时钟引发的事情
查看>>
JPEG和Variant的转换
查看>>
How to read very large text files fast
查看>>
Java读取.properties配置文件
查看>>
java绘制带姓的圆
查看>>
android数据的4种存储方式
查看>>
css缓存问题
查看>>
3dmax_FBX转havok_model
查看>>
Linux常用命令
查看>>
实验三 二叉树
查看>>
几种交叉验证(cross validation)方式的比较
查看>>
第44章:MongoDB-集群--Sharding(分片)--分片的片键选择
查看>>
自定义ISO结构
查看>>
7.11 animals.c 程序
查看>>
java Web三大组件--过滤器
查看>>
使用NUnit为游戏项目编写高质量单元测试的思考
查看>>
Uva 1638 Pole Arrangement
查看>>
Java内存泄漏
查看>>
逻辑函数的代数化简法
查看>>