来做一个NLP任务

  步骤为:
    1.读取文件;
    2.去除所有标点符号和换行符,并把所有大写变成小写;
    3.合并相同的词,统计每个词出现的频率,并按照词频从大到小排序;
    4.将结果按行输出到文件 out.txt。
  代码:
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 的基本数据类型。

  同样的,Json序列化与反序列化时也要注意做错误处理,比如json.loads('123.2')会返回一个float类型。因此反序列化后需要判断是否期望的类型:
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)的更多相关文章

  1. Python基础篇(格式化输出,运算符,编码):

    Python基础篇(格式化输出,运算符,编码): 格式化输出: 格式:print ( " 内容%s" %(变量)) 字符类型: %s  替换字符串      %d 替换整体数字  ...

  2. C#语言基础— 输入与输出

    C#语言基础— 输入与输出 1.1函数的四要素:名称.输入.输出.加工 1.2主函数:输出语句.输入语句: Static viod Main(string[] stgs)//下划线部分可以自己指定 { ...

  3. python 3 输入和输出

    一.普遍的输入和输出 1.输入 在python3中,函数的输入格式为:input(),能够接受一个标准输入数据,返回string类型. input() 函数是从键盘作为字符串读取数据,不论是否使用引号 ...

  4. python基础_格式化输出(%用法和format用法)(转载)

    python基础_格式化输出(%用法和format用法) 目录 %用法 format用法 %用法 1.整数的输出 %o -- oct 八进制%d -- dec 十进制%x -- hex 十六进制 &g ...

  5. Python的输入和输出问题详解

    输出用print()在括号中加上字符串,就可以向屏幕上输出指定的文字.比如输出'hello, world',用代码实现如下: >>> print('hello, world') pr ...

  6. Python学习——输入和输出

    (转自:http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014316434841 ...

  7. 2.Python基础认识(格式化输出,while语句,运算符,编码,单位转化)

    Python基础认识 1.字符串的格式化初识及占位符的简单应用 字符串的格式化 按照既定的要求进行有规定排版的一种输出方式. #我们想要输出的格式如下: ----------------------- ...

  8. python基础(5):格式化输出、基本运算符、编码问题

    1. 格式化输出 现在有以下需求,让⽤户输入name, age, job,hobby 然后输出如下所⽰: ------------ info of Alex Li ----------- Name : ...

  9. python文件输入和输出

    1.1文件对象 文件只是连续的字节序列.数据的传输经常会用到字节流,无论字节流是由单个字节还是大块数据组成.1.2文件内建函数open()和file() 内建函数open()的基本语法是: file_ ...

随机推荐

  1. 记一次内存溢出java.lang.OutOfMemoryError: unable to create new native thread

    一.问题: 春节将至,系统访问量进入高峰期.随之系统出现了异常:java.lang.OutOfMemoryError: unable to create new native thread.在解决这个 ...

  2. Unity Download Assistant Error: 'SendRequest Error' while downloading ini file from http://files.unity3d.com/bootstrapper/29055738eb78/unity-5.3.6f1-win.ini

    Unity 官网的哥们如此说道 I open the exe on Compatibility Mode , it's solved. You can try. :) 翻译就是 我用兼容模式打开,就能 ...

  3. 自定义控件使用GDI+绘制旋转Label文字

    http://www.cnblogs.com/CUIT-DX037/ 1.添加用户控件: 2.添加代码: public partial class UcLabel : UserControl { pu ...

  4. Android图表库XCL-Charts

    首先,这个是国人开发的,支持下必须顶!github项目地址:点击打开,由于项目的基本功能已经实现,所以项目作者也说以后基本不会在有更新了. 项目简介: Android图表库(XCL-Charts is ...

  5. HhashMap HashTable ConcurrentHashMap

    hashMap hashTable concurrentHashMap hashMap的效率高于hashTable,hashMap是线程不安全的,并发时hashMap put方法容易引起死循环,导致c ...

  6. linux 跳过登陆修改用户密码

      2017-02-11 20:41 6人阅读 评论(0) 收藏 编辑 删除  分类: Linux 版权声明:本文为博主原创文章,未经博主允许不得转载. Linux 系统默认的是有0 1 2  3   ...

  7. Cocos2d-x v3.1 坐标系统(五)

    Cocos2d-x v3.1 坐标系统(五) 为了能够更好的布局以及了解对象所在的位置,我们必须对Cocos2d-x中的坐标有详细的了解,本篇文章主要就是了解Cocos中用到的坐标系统.学过数学的人都 ...

  8. C++编写字符串类CNString,该类有默认构造函数、类的拷贝函数、类的析构函数及运算符重载

    编码实现字符串类CNString,该类有默认构造函数.类的拷贝函数.类的析构函数及运算符重载,需实现以下“=”运算符.“+”运算.“[]”运算符.“<”运算符及“>”运算符及“==”运算符 ...

  9. 杭电acm刷题顺序

    最近兴趣来了,闲暇之余,回顾大学期间刷过的杭电acm那些入门级别的题,以此巩固基础知识! 以下参考刷题顺序,避免入坑 原文传送门:https://blog.csdn.net/liuqiyao_01/a ...

  10. LeetCode Single Number III (xor)

    题意: 给一个数组,其中仅有两个元素是出现1次的,且其他元素均出现2次.求这两个特殊的元素? 思路: 跟查找单个特殊的那道题是差不多的,只是这次出现了两个特殊的.将数组扫一遍求全部元素的异或和 x,结 ...