Python核心丨输入与输出

输入与输出


输入输出基础

最简单直接的输入来子键盘操作

name = input('your name:')
gender = input('you are a boy?(y/n)')

###### 输入 ######
your name:Jack
you are a boy?(y/n) y

welcome_str = 'Welcome to the matrix {prefix} {name}.'
welcome_dit = {
    'prefix': 'Mr.' if gender == 'y' else 'Mrs',
    'name': name
}

print('authorizing...')
print(welcome_str.format(**welcome_dic))

########## 输出 ##########
autohrizing...
Welcome to the matrix Mr.Jack

input()函数暂停程序运行,同时等待键盘输入;直到回车被按下,函数的参数即为提示语,输入的类型永远是字符串型(str)

示例

a = input()
1
b = input()
2

print('a + b = {}'.format(a + b))
########## 输出 ##########
a + b = 12

print('type of a is {}, type of b is {}'.format(tpye(a), type(b)))
########## 输出 ##########
type of a is <class 'str'>, type of b is <class 'str'>

print('a + b = {}'.format(int(a) + int(b)))
########## 输出 ##########
a + b = 3

注:把str强制转换为int用int(),转为浮点数用float()。在生产环境中使用强制转换时,记得加上try except

Python对int类型没有最大限制,但是对float类型依然有精度限制。

在生产环境中要时刻提防,避免因为对边界条件判断不清而造成bug甚至Oday(危重安全漏洞)

2018 年 4 月 23 日中午 11 点 30 分左右,BEC 代币智能合约被黑客攻击。黑客利用数据溢出的漏洞,攻击与美图合作的公司美链 BEC 的智能合约,成功地向两个地址转出了天量级别的 BEC 代币,导致市场上的海量 BEC 被抛售,该数字货币的价值也几近归零,给 BEC 市场交易带来了毁灭性的打击。

文件输入输出

生产级别的Python代码,大部分I/O则来自文件、网络、其他进程的消息等等

文本文件in.txt

I have a dream that my four little children will one day live in a nation where they will not be judged by the color of their skin but by the content of their character. I have a dream today.

I have a dream that one day down in Alabama, with its vicious racists, . . . one day right there in Alabama little black boys and black girls will be able to join hands with little white boys and white girls as sisters and brothers. I have a dream today.

I have a dream that one day every valley shall be exalted, every hill and mountain shall be made low, the rough places will be made plain, and the crooked places will be made straight, and the glory of the Lord shall be revealed, and all flesh shall see it together.

This is our hope. . . With this faith we will be able to hew out of the mountain of despair a stone of hope. With this faith we will be able to transform the jangling discords of our nation into a beautiful symphony of brotherhood. With this faith we will be able to work together, to pray together, to struggle together, to go to jail together, to stand up for freedom together, knowing that we will be free one day. . . .

And when this happens, and when we allow freedom ring, when we let it ring from every village and every hamlet, from every state and every city, we will be able to speed up that day when all of God's children, black men and white men, Jews and Gentiles, Protestants and Catholics, will be able to join hands and sing in the words of the old Negro spiritual: "Free at last! Free at last! Thank God Almighty, we are free at last!"

进行一个简单的NLP(自然语言处理)任务。

NLP任务的基本步骤:

1、读取文件
2、去除所有标点符号和换行符,并把所有大写变成小写
3、合并相同的词,统计每个词出现的频率,并按照词频从大到小排序
4、将结果按行输出到文件out.txt

import re

def parse(text):
    # 使用正则表达式去除标点符合和换行符
    text = re.sub(r'[^\w]', ' ', text)

    # 转为小写
    text = text.lower()
   
    # 生成单词和词频的字典
    word_cnt = {}
    for word in word_list:
        if word not in word_cnt:
            word_cnt[word] = 0
        word_cnt[word] += 1
 
    # 按照词频排序
    sorted_word_cnt = sorted(word_cnt.items(), key=lambda kv:kv[1], reverse=True)

    return sorted_word_cnt
 
with open('in.txt', 'r'as fin:
    text = fin.read()

word_and_freq = parse(text)

with open('out.txt', 'w') as fout:
    for word, freq in word_and_freq:
        fout.write('{} {}\m'.format(word, freq))

parse()函数是把输入的text字符串转换为排序后的词频统计。

sorted_word_cnt是一个二元组的列表

用open()函数拿到文件的指针。第一个参数指定文件位置,第二个参数,"r"表示读取,"w"表示写入。

拿到指针后,通过read()函数,读取全部内容,即表示把文件所有内容读取到内存中,并赋值给变量text。

优缺点:

  • 有点:方便,可以直接调用parse函数进行分析
  • 缺点:如果文件过大,可能会造成内存崩溃

解决办法:

  • 可以给read指定参数size,表示读取的最大长度
  • 还可以通过readline()函数,每次读取一行
JSON序列化

JSON(JavaScript Object Notation)是一种轻量级的数据交换格式。

设计意图是把所有事情都用设计的字符串来表示,即方便在互联网上传递信息,也方便人进行阅读。

场景:

  • 向交易所购买一定数额的股票。需要提交股票代码、方向、订单类型、加格、数量等一些列参数,而这些数据里,有字符串,有整数。浮点数,甚至还有布尔值,全部混在一起并不方便交易所解包

JSON便可以解决这个场景,可以把它理解为两种黑箱

  • 输入这些杂七杂八的信息,如Python字典,输出一个字符串;
  • 输入这个字符串,可以输出包含原始信息的Python字典;
import json
 
 params = {
     'symbol': '123456',
     'type': 'limit',
     'price': 123.4,
     'amount': 23
 }
params_str = json.dumps(params)

print('after json serialzation')
print('type of params_str = {},params_str = {}'.format(type(params_str), params)

original_params = json.load(params_str)

print('after json deserialization)
print('type of original_params = {}, original_params = {}'.format(tpye(original_params, original_params))

########## 输出 ##########
after json serialization 
type of params_str = <class 'str'> , params_str = {'symbol': '123456', 'type': 'limit', 'price': 123.4, 'amount': 23}
after json deserialization
type of original_params = <class 'dict'>, original_params = {'symbol': '123456', 'type': 'limit', 'price': 123.4, 'amount': 23}

其中

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

注:记得加上错误处理,不然给json.loads()发送一个非法字符串,没有catch到,程序就会崩溃。

输入字符串到文件,或者从文件中读取JSON字符串


import json

params = {
    'symbol': '123456',
    'type': 'limit',
    'price': 123.4,
    'amount': 23
}

with open('params.json', 'w') as fout:
    params_str = json.dump(params, fout)

with open('params.json', 'r') as fin:
    original_params = json.load(fin)

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}

当开发第三方应用程序时,可以通过JSON将用户的个人配置输出到问就按,方便下次程序启动时自动读取。

另外,JSON并不是唯一的选择,它只是轻量级应用中最方便的选择之一。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值