Python基础:输入与输出(I/O)
来做一个NLP任务
import re
import 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_cnt inFile = '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 defaultdict
import re,sys,os inFile = '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] += 1 outFile = '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 的基本数据类型。
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,sys
params = {
'symbol': '',
'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 = <class '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 = <class 'dict'>, original_params = {'symbol': '123456', 'type': 'limit', 'price': 123.4, 'amount': 23}
参考资料:
极客时间《Python核心技术与实战》
Python基础:输入与输出(I/O)的更多相关文章
- Python基础篇(格式化输出,运算符,编码):
Python基础篇(格式化输出,运算符,编码): 格式化输出: 格式:print ( " 内容%s" %(变量)) 字符类型: %s 替换字符串 %d 替换整体数字 ...
- C#语言基础— 输入与输出
C#语言基础— 输入与输出 1.1函数的四要素:名称.输入.输出.加工 1.2主函数:输出语句.输入语句: Static viod Main(string[] stgs)//下划线部分可以自己指定 { ...
- python 3 输入和输出
一.普遍的输入和输出 1.输入 在python3中,函数的输入格式为:input(),能够接受一个标准输入数据,返回string类型. input() 函数是从键盘作为字符串读取数据,不论是否使用引号 ...
- python基础_格式化输出(%用法和format用法)(转载)
python基础_格式化输出(%用法和format用法) 目录 %用法 format用法 %用法 1.整数的输出 %o -- oct 八进制%d -- dec 十进制%x -- hex 十六进制 &g ...
- Python的输入和输出问题详解
输出用print()在括号中加上字符串,就可以向屏幕上输出指定的文字.比如输出'hello, world',用代码实现如下: >>> print('hello, world') pr ...
- Python学习——输入和输出
(转自:http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014316434841 ...
- 2.Python基础认识(格式化输出,while语句,运算符,编码,单位转化)
Python基础认识 1.字符串的格式化初识及占位符的简单应用 字符串的格式化 按照既定的要求进行有规定排版的一种输出方式. #我们想要输出的格式如下: ----------------------- ...
- python基础(5):格式化输出、基本运算符、编码问题
1. 格式化输出 现在有以下需求,让⽤户输入name, age, job,hobby 然后输出如下所⽰: ------------ info of Alex Li ----------- Name : ...
- python文件输入和输出
1.1文件对象 文件只是连续的字节序列.数据的传输经常会用到字节流,无论字节流是由单个字节还是大块数据组成.1.2文件内建函数open()和file() 内建函数open()的基本语法是: file_ ...
随机推荐
- Hadoop InputFormat详解
InputFormat是MapReduce编程模型包括5个可编程组件之一,其余4个是Mapper.Partitioner.Reducer和OutputFormat. 新版Hadoop InputFor ...
- VMWare复制虚拟机系统后,模块“Disk”无法启动【转】
1.找到虚拟机所在的目录 将 .vmx文件打开 将文件vmci0.present = "TRUE" 改为 vmci0.present = "FALSE" 2.删 ...
- 性能测试学习第四天_Loadrunner概述
1.Loadrunner的组成部分 ·脚本生成器VuGen:virtual user generator ·压力控制器Controller,License主要在这里控制 ·结果分析软件Analysis ...
- Windows下使用beego遇到的问题
一.解决:cc1.exe: sorry, unimplemented: 64-bit mode not compiled in: 参考链接:http://blog.csdn.net/mecho/art ...
- Ashx增删改查_动软
1.首先展示列表 ashx 讲究的是个替换 这些就是属于ashx麻烦的地方 public void ProcessRequest(HttpContext context) { context.Resp ...
- sublime 主要使用方法
---------------最常用的1.新建文件-输入"html:xt"后 按"Ctrl+E键"或 "tab键" ,可快速生成xhtml ...
- 在浏览器地址栏按回车、F5、ctrl+F5刷新页面的区别
url地址栏里敲击enter:这样的刷新,大家可以在firebug里看一下,只有少数的请求会发送出去,而且几乎没有图片的请求,这是因为请求时会先检查本地是不是缓存了请求的图片,如果有缓存而且没有过期( ...
- 前端三剑客之javascript
前端三剑客之javascript 给个小目录 一.JavaScript介绍 二.ECMAScript(核心) 三.BOM对象(浏览器对象) 四.DOM对象(文档对象模型) 总结: JS的组成: a ...
- iOS 解决tableView中headerView头部视图不跟随tableView滑动的方法
解决方法如下: if (scrollView.contentOffset.y >= 0 && scrollView.contentOffset.y <= pushNewsT ...
- AppScale3.01
平台: Ubuntu 类型: 虚拟机镜像 软件包: appscale appscale-tools app appscale appserver basic software cloud comput ...