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_ ...
随机推荐
- 【Windows】命令行查询占用端口信息
Windows上查询443端口被占用的信息: NETSTAT.EXE -nao | findstr "443" 查询结果 杀掉进程: tskill 2888
- matlab 常用函数(数学建模-复习)
常用函数 fscanf(fid, '%c', inf) -> 直接读取整个文件, 因为inf表示无穷 strtrim char(num): 将num转为ASCII字符 strtok(conten ...
- KendoUI 自定义验证:
Html: <label>@LogicNameAttribute.GetLogicName(typeof(Reward).GetProperty("ExtraRewardMone ...
- Cmd命令 关机
at 22:00 Shutdown -s 到了22点电脑就会出现"系统关机"对话框,默认有30秒钟的倒计时并提示你保存工作 Shutdown.exe -s -t 3600 这里表示 ...
- sublime 常用快捷键(转)
Sublime text 3是码农最喜欢的代码编辑器,每天和代码打交道,必先利其器,掌握基本的代码编辑器的快捷键,能让你打码更有效率.刚开始可能有些生疏,只要花一两个星期坚持使用并熟悉这些常用的快捷键 ...
- php 出现空格,换行原因
1.空格:转换成utf-8无bom格式 2.空格:<?php ?>标签结尾有中文,英文空格 3.换行,一个文件中有多个<?php ?>标签,标签间隔中有换行符合
- repair table
mysql> show create table lixl;+-------+---------------------------------------------------------- ...
- hiho一下 第三十九周 归并排序求逆序数
题目链接:http://hihocoder.com/contest/hiho39/problem/1 ,归并排序求逆序数. 其实这道题也是可以用树状数组来做的,不过数据都比较大,所以要离散化预处理一下 ...
- java Vamei快速教程10 接口的继承和抽象类
作者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明.谢谢! 在实施接口中,我们利用interface语法,将interface从类定义中独立出 ...
- ffmpeg 资源[转]
http://blog.csdn.net/leixiaohua1020/article/details/15811977 一. FFmpeg主站 1. FFmpeg的源码发布,资料 网址: htt ...