您好,登錄后才能下訂單哦!
小編給大家分享一下如何用python輸出和輸入文件及信息,希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去探討吧!
利用語句有:input和print語句
關于Input代碼演示:
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.
input函數暫停運行,等待鍵盤輸入,直到按下回車,輸入的類型永遠是字符串
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
文件輸入和輸出
生產級別的 Python 代碼,大部分 I/O 則來自于文件,這里有個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
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)) ########## 輸出 (省略較長的中間結果) ##########
看完了這篇文章,相信你對如何用python輸出和輸入文件及信息有了一定的了解,想了解更多相關知識,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。