Python基础:输入与输出(I/O) 阅读目录

来做一个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}")

假如文件非常大,一次性读取可能会导致内存崩溃,那么可以用一行一行读取的方法来实现:

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006 寻找有志同道合的小伙伴,
互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
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': '123456',
'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}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值