【Python学習】インプットとアウトプット

序文

以前の記事

【Python学習】リストとタプル

【Python学習】辞書とコレクション

【Python学習】条件とループ

多くの場合、プログラムでユーザー (おそらく自分自身) と対話する必要があります。ユーザーから入力を取得し、いくつかの結果を出力します。iinput および print ステートメントを使用して、これらの機能を実行できます。

入力

name = input('your name:')
gender = input('you are a boy?(y/n)')

###### 输入 ######
your name:Jack
you are a boy?

welcome_str = 'Welcome to the matrix {prefix} {name}.'
welcome_dic = {
    
    
    'prefix': 'Mr.' if gender == 'y' else 'Mrs',
    'name': name
}

print('authorizing...')
print(welcome_str.format(**welcome_dic))

########## 输出 ##########
authorizing...
Welcome to the matrix Mr. Jack.

入力関数は一時停止し、Enter キーが押されるまでキーボード入力を待機します。入力のタイプは常に文字列です。

a = input()
1
b = input()
2

print('a + b = {}'.format(a + b))
########## 输出 ##############
a + b = 12
print('type of a is {}, type of b is {}'.format(type(a), type(b)))
########## 输出 ##############
type of a is <class 'str'>, type of b is <class 'str'>
print('a + b = {}'.format(int(a) + int(b)))
########## 输出 ##############
a + b = 3

ファイルの入出力

ほとんどの I/O がファイルから発生するプロダクション グレードの Python コード

これがin.textです

Mr. Johnson had never been up in an aerophane before and he had read a lot about air accidents, so one day when a friend offered to take him for a ride in his own small phane, Mr. Johnson was very worried about accepting. Finally, however, his friend persuaded him that it was very safe, and Mr. Johnson boarded the plane.

His friend started the engine and began to taxi onto the runway of the airport. Mr. Johnson had heard that the most dangerous part of a flight were the take-off and the landing, so he was extremely frightened and closed his eyes.

After a minute or two he opened them again, looked out of the window of the plane, and said to his friend。

"Look at those people down there. They look as small as ants, don't they?"

"Those are ants," answered his friend. "We're still on the ground."

  • ファイルを読む
  • すべての句読点と改行を削除し、大文字を小文字に変更します
  • 同じ単語をマージし、各単語の頻度をカウントし、頻度の多い単語から少ない単語へと並べ替えます
  • 結果をファイル out.txt に 1 行ずつ出力する
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:
        if word not in word_cnt:
            word_cnt[word] = 0
        word_cnt[word] += 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))

########## 输出 (省略较长的中间结果) ##########



ただし、ファイルが非常に大きい場合、メモリ クラッシュが発生しやすいという問題があります。

このとき、read のパラメータ size を指定します readline() 関数を使用して 1 行ずつ読み込むこともできます。

jsonファイルの読み取り

import json

params = {
    
    
    'symbol': '123456',
    'type': 'limit',
    'price': 123.4,
    'amount': 23
}

params_str = json.dumps(params)

print('after json serialization')
print('type of params_str = {}, params_str = {}'.format(type(params_str), params))

original_params = json.loads(params_str)

print('after json deserialization')
print('type of original_params = {}, original_params = {}'.format(type(original_params), original_params))

########## 输出 ##########

after json serialization
type of params_str = <class 'str'>, params_str = {
    
    'symbol': '123456', 'type': 'limit', 'price': 123.4, 'amount': 23}
after json deserialization
type of original_params = <class 'dict'>, original_params = {
    
    'symbol': '123456', 'type': 'limit', 'price': 123.4, 'amount': 23}

json.dumps() この関数は、Python の基本的なデータ型辞書を受け入れ、文字列 (json 文字列) を変換します

json.loads() この関数は正当な文字列 (json) を受け取り、それを辞書に変換します

jsonの読み取り

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}

おすすめ

転載: blog.csdn.net/yxczsz/article/details/128662603