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_ ...
随机推荐
- python学习二(文件与异常)
Python中使用open BIF与文件交互,与for语句结合使用,一次读取一行 读取文件sketch.txt,文件内容如下: Man: Ah! (taking out his wallet and ...
- 网络爬虫之记一次js逆向解密经历
1 引言 数月前写过某网站(请原谅我的掩耳盗铃)的爬虫,这两天需要重新采集一次,用的是scrapy-redis框架,本以为二次爬取可以轻松完成的,可没想到爬虫启动没几秒,出现了大堆的重试提示,心里顿时 ...
- 使用jQuery实现文本框input定位到文字最后(兼容所有浏览器)
$.fn.setCursorPosition = function(position){ if(this.lengh == 0) return this; return $(this).setSele ...
- IOS NSTimer 定时器用法总结
NSTimer在IOS开发中会经常用到,尤其是小型游戏,然而对于初学者时常会注意不到其中的内存释放问题,将其基本用法总结如下: 一.初始化方法:有五种初始化方法,分别是 + (NSTimer *)ti ...
- Ecshop如何解决Deprecated: preg_replace()报错
今天安装Ecshop后,运行出现各种问题,其中 Deprecated: preg_replace() 之类的报错最多,下面贴出解决方案: 错误原因: preg_replace() 函数中用到的修饰符 ...
- smarty基本用法
简介: 1.smarty语法:它是php的一种模板引擎 它的设计特点是:业务逻辑与显示逻辑分离 Smarty的标签都是使用定界符{ }括起来注释:{* 我是Smarty的注释内容 *} <u ...
- 【mysql】mysql 配置
安装完mysql后, 要及得配置一下 /etc/mysql/my.cnf 配置字符编码为utf8 [client] default-character-set = utf8 [mysqld] defa ...
- 【干货】JavaScript DOM编程艺术学习笔记7-9
七.动态创建标记 在文档中不写占位图片和文字代码,在能调用js的情况下动态创建,文档支持性更好. 在原来的addLoadEvent prepareGallery showPic的基础上增加函数prep ...
- git版本分支和分支、分支和主分支切换
问题描述: 公司里项目管理使用的是gitLab(收费的), 如果开发人员提交代码, 需要首先创建一个分支, 然后把代码提交到你创建的分支上去(不允许把代码直接提交到主分支上). 在代码提交到已经创建 ...
- 《Python高效开发实战》实战演练——基本视图3
在完成Django项目和应用的建立后,即可以开始编写网站应用代码,这里通过为注册页面显示一个欢迎标题,来演示Django的路由映射功能. 1)首先在djangosite/app/views.py中建立 ...