点击上方Python知识圈,设为星标

回复1024获取Python资料

阅读文本大概需要 5 分钟

近期精彩文章Python100例(附PDF下载地址)

在很多时候,你会想要让你的程序与用户(可能是你自己)交互。你会从用户那里得到输入,然后打印一些结果。我们可以使用input和print语句来完成这些功能。

input

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

###### 输入 ######your name:Runsenyou are a boy?:y

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

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

########## 输出 ##########authorizing...Welcome to the matrix Mr. Runsen.

input函数暂停运行,等待键盘输入,直到按下回车,输入的类型永远时字符串

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

print('a + b = {}'.format(a + b))########## 输出 ##############a + b = 12print('type of a is {}, type of b is {}'.format(type(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

文件输入和输出

生产级别的 Python 代码,大部分 I/O 则来自于文件

这里有个in.text,完成worldcount功能。

Mr. Johnson had never been up in an aerophane before and he had read a lot about air accidents, so one day when a friend offered to take him for a ride in his own small phane, Mr. Johnson was very worried about accepting. Finally, however, his friend persuaded him that it was very safe, and Mr. Johnson boarded the plane.

His friend started the engine and began to taxi onto the runway of the airport. Mr. Johnson had heard that the most dangerous part of a flight were the take-off and the landing, so he was extremely frightened and closed his eyes.

After a minute or two he opened them again, looked out of the window of the plane, and said to his friend。

"Look at those people down there. They look as small as ants, don't they?"

"Those are ants," answered his friend. "We're still on the ground."

现在

  • 读取文件
  • 去掉所有标点和换行符,将大写变为小写
  • 合并相同的词,统计每个词出现的频率,将词频从大到小排序
  • 将结果按行输出文件out.txt
import re

# 你不用太关心这个函数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

    # 按照词频排序    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('{} {}\n'.format(word, freq))

########## 输出 (省略较长的中间结果) ##########


但是有个问题,如果文件非常的大容易造成内存奔溃

这个时候给 read 指定参数 size,还可以通过 readline() 函数,每次读取一行。

json文件读取

import json

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

params_str = json.dumps(params)

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

original_params = json.loads(params_str)

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

########## 输出 ##########

after json serializationtype of params_str = <class 'str'>, params_str = {'symbol': '123456', 'type': 'limit', 'price': 123.4, 'amount': 23}after json deserializationtype of original_params = <class 'dict'>, original_params = {'symbol': '123456', 'type': 'limit', 'price': 123.4, 'amount': 23}

json.dumps() 这个函数,接受 Python 的基本数据类型 字典,然后转化string (json的字符串)

json.loads() 这个函数,接受一个合法字符串(json),然后 转化为字典

「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 deserializationtype of original_params = <class 'dict'>, original_params = {'symbol': '123456', 'type': 'limit', 'price': 123.4, 'amount': 23}

参考:https://time.geekbang.org/column/article/96570

-----------------------公众号:Python知识圈博客:www.pyzhishiquan.com知乎:Python知识圈微信视频号:菜鸟程序员 (分享有趣的编程技巧、Python技巧)bilibili:菜鸟程序员的日常(目前原创视频:22,累计播放量:85万)

我的微信视频号定时更新中,近期真人出镜分析讲解 Python 经典习题,后续会分享更多的干货,欢迎关注我的微信视频号。

Python知识圈公众号的交流群已经建立,群里可以领取 Python 相关学习资料,大家可以一起学习交流,效率更高,如果是想发推文、广告、砍价小程序的敬请绕道!一定记得备注「交流学习」,不然不会通过好友。

扫码添加,备注:交流学习

往期推荐01

公众号所有文章汇总导航(2-10更新)

02

Python100例(附PDF下载地址)

03

打基础一定要吃透这12类 Python 内置函数

↓点击阅读原文查看pk哥原创视频

我就知道你“在看”

python 去除字符串的标点符号 用_Python输入和输出相关推荐

  1. [转载] [转载] python 去除字符串的标点符号 用_Python成为专业人士笔记–String字符串方法

    参考链接: Python字符串| 十六进制 hexdigits 参考链接: Python的字符串Strings decode "专业人士笔记"系列目录: 创帆云:Python成为专 ...

  2. [转载] python 去除字符串的标点符号 用_Python成为专业人士笔记–String字符串方法

    参考链接: Python的字符串Strings decode "专业人士笔记"系列目录: 创帆云:Python成为专业人士笔记--强烈建议收藏!每日持续更新!​zhuanlan.z ...

  3. python 去除字符串的标点符号 用_7步搞定数据清洗-Python数据清洗指南

    脏数据就是在物理上临时存在过,但在逻辑上不存在的数据. 数据清洗是整个数据分析过程的第一步,就像做一道菜之前需要先择菜洗菜一样. 数据分析师经常需要花费大量的时间来清洗数据或者转换格式,这个工作甚至会 ...

  4. python去除字符串两边的空格_Python去除字符串两端空格的方法

    <Python Cookbook(第2版)中文版>--1.5 去除字符串两端的空格 本节书摘来自异步社区<Python Cookbook(第2版)中文版>一书中的第1章,第1. ...

  5. python将学号与成绩匹配_python输入学号输出成绩等级_python将百分制成绩转换为等级制输出...

    展开全部 1.def main(): score = float(input('请输入成绩: ')) if score >= 90: grade = 'A' elif score >= 8 ...

  6. python去除字符串两边空格_Python去除字符串两端空格的方法

    Python去除字符串两端空格的方法 目的 获得一个首尾不含多余空格的字符串 方法 可以使用字符串的以下方法处理: string.lstrip(s[, chars]) Return a copy of ...

  7. Python 去除字符串中空格(删除指定字符)的3种方法

    文章目录 Python 去除字符串中空格 Python strip()方法 Python lstrip()方法 Python rstrip()方法 Python 去除字符串中空格 用户输入数据时,很有 ...

  8. python去除字符串中表情字符

    python去除字符串中表情字符 用mysql存储数据时,"charset=utf8"默认状态下text字段不支持4字节的字符,而表情字符为4字节,如果表情字符非所需数据时可以将其 ...

  9. python去掉两边空格,Python去除字符串两端空格的方法

    这篇文章主要介绍了Python去除字符串两端空格的方法,本文主要讲解了string.lstrip.string.rstrip.string.strip等函数的运用,需要的朋友可以参考下 目的 获得一个 ...

最新文章

  1. jQuery Event对象的属性和方法
  2. golang中的sync.Map
  3. 【Alpha阶段】第六次Scrum Meeting
  4. 数十亿次数学运算只消耗几毫瓦电力,谷歌开源Pixel 4背后的视觉模型
  5. Kaggle 官方教程:嵌入
  6. JAVA求数组的平均数,众数,中位数
  7. 【微软黑科技一周概览】
  8. 长肥管道(LFT)中TCP的艰难处境与打法
  9. android控件触摸事件传递,Android事件传递处理
  10. php入门案例,thinkphp3.2.1入门之--简单案例实现
  11. 黑客挂马木马病毒研究 黑客木马的攻击与防止 木马的威力 木马运作流程 黑客的高明 社工学用户行为分析...
  12. 基于二叉链表的二叉树最大宽度的计算
  13. 完整HTML实例网页代码(1)
  14. Linux vi 查找和替换字符串
  15. 用Unity的GetSpectrumData方法识别钢琴曲中的钢琴琴键
  16. win7共享计算机打不开,windows7共享文件夹打不开怎么办
  17. android studio 把libs包打包到apk中,设置应用以32bit去读取.so文件
  18. KernelGAN论文详解分享
  19. 除了独热编码,你需要了解将分类特征转换为数字特征的17种方法--较详细说明各方法的优点
  20. python笔记-Pygame详解(十七):joystick 模块

热门文章

  1. 浅析NameNode/DataNode/SecondaryNameNode源码注释
  2. 面试必会系列 - 1.3 Java 多线程
  3. 多线程与高并发(一):单机高并发应该掌握的线程基础:线程状态,异常与锁等
  4. Copy-On-Write读写分离策略和CopyOnWriteArrayList源码分析
  5. postman添加cookie
  6. commons-lang3工具类学习(一)
  7. 02.uri-search
  8. [leetcode]15.三数之和
  9. mac11.5.2版本虚拟机SeaBIOS不引导,kvm虚拟机状态为pause
  10. Mysql数据库函数(数字,字符串,日期时间)