您好,登錄后才能下訂單哦!
小編給大家分享一下如何用python輸出和輸入文件及信息,希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去探討吧!
利用語句有:input和print語句
關(guān)于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函數(shù)暫停運(yùn)行,等待鍵盤輸入,直到按下回車,輸入的類型永遠(yuǎn)是字符串
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
文件輸入和輸出
生產(chǎn)級(jí)別的 Python 代碼,大部分 I/O 則來自于文件,這里有個(gè)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."
現(xiàn)在讀取文件:
去掉所有標(biāo)點(diǎn)和換行符,將大寫變?yōu)樾?/span>
合并相同的詞,統(tǒng)計(jì)每個(gè)詞出現(xiàn)的頻率,將詞頻從大到小排序
將結(jié)果按行輸出文件out.txt
import re # 你不用太關(guān)心這個(gè)函數(shù) def parse(text): # 使用正則表達(dá)式去除標(biāo)點(diǎn)符號(hào)和換行符 text = re.sub(r'[^\w ]', '', text) # 轉(zhuǎn)為小寫 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)) ########## 輸出 (省略較長(zhǎng)的中間結(jié)果) ##########
看完了這篇文章,相信你對(duì)如何用python輸出和輸入文件及信息有了一定的了解,想了解更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。