赞
踩
首先,我们要清楚 NLP 任务的基本步骤,也就是下面的四步:
接下来,我们来详细分析一个文本文件读写。假设我们有一个文本文件 in.txt,内容如下:
May you have enough happiness to make you sweet,enough trials to make you strong,enough sorrow to keep you human,enough hope to make you happy?
Always put yourself in others’shoes.If you feel that it hurts you,it probably hurts the other person, too.
代码:
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: word_cnt[word] = word_cnt.get(word, 0) + 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))
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.dumps() 这个函数,接受 Python 的基本数据类型(列表等都行),然后将其序列化为 string;
而 json.loads() 这个函数,接受一个合法字符串,然后将其反序列化为 Python 的基本数据类型。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。