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}")
  假如文件非常大,一次性讀取可能會導致內存崩潰,那么可以用一行一行讀取的方法來實現:
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}

 

 

參考資料:

極客時間《Python核心技術與實戰》


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM