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_ ...
随机推荐
- var obj = eval(result); 解析json
l var obj = eval(result);解析json
- IDEA/Eclipse安装 Alibaba Java Coding Guidelines 插件
为了让开发者更加方便.并且达到快速规范代码格式的目的并实行起来,阿里巴巴基于<阿里巴巴Java开发规约>手册内容,研发了一套自动化的IDE检测插件(IDEA.Eclipse).它就是Ali ...
- POJ 2253 ——Frogger——————【最短路、Dijkstra、最长边最小化】
Frogger Time Limit:1000MS Memory Limit:65536KB 64bit IO Format:%I64d & %I64u Submit Stat ...
- VUE打包发布后无法访问js、css资源
在vue开发中,本地测试以及测试环境中都没有遇到问题,当发布生产,有虚拟路径时,便出现js.css均报错404: 首先在config的index.js文件中,将assetsPublicPath修改为' ...
- Hibernate笔记7--JPA CRUD
1.环境搭建,注意包结构的问题,src下建立名为META-INF的文件夹,放persistence.xml,位置放错,读不到会报错. <?xml version="1.0" ...
- /etc/syslog.conf日志配置文件详解
//将info或更高级别的消息送到/var/log/messages,除了mail以外. //其中*是通配符,代表任何设备:none表示不对任何级别的信息进行记录. *.info;mail.none; ...
- 如何在Ubuntu server中修改IP
详细请移步至博客https://blog.csdn.net/shenzhen_zsw/article/details/74025066 方法一. sudo ifconfig eth0 100.100 ...
- IOS plist的数据 存 取(沙河目录)
应用沙盒目录的常见获取方式 沙盒根目录:NSString *home = NSHomeDirectory(); Documents:(2种方式) 1.利用沙盒根目录拼接”Documents”字符串 N ...
- select into outfile
语法格式如下: SELECT [列名] FROM table [WHERE 语句] INTO OUTFILE '目标文件' [OPTION]; FIELDS TERMINATED ...
- mongostat查看mongodb运行状态使用命令介绍
mongostat是mongodb自带的一个用来查看mongodb运行状态的工具 使用说明 mongostat -h 字段说明 启用后的状况是这样的 insert query update del ...