来做一个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': '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}
参考资料: