內(nèi)容來源于網(wǎng)絡(luò)厦凤,本人只是在此稍作整理肤寝,如有涉及版權(quán)問題,歸小甲魚官方所有字逗。
練習(xí)題(來自小甲魚官方論壇)
編程題
0. 編寫一個程序京郑,接受用戶的輸入并保存為新的文件,程序?qū)崿F(xiàn)如圖:
(圖片轉(zhuǎn)自https://blog.csdn.net/junwei0206/article/details/44988195)
答:代碼如下:
def filewrite(file_name):
print('請輸入內(nèi)容【單獨輸入‘:w’保存退出】:')
f = open(file_name, 'w')
while True:
a = input()
if a != ':w':
f.write('%s\n' % a) # 注意這里有換行符
else:
break
f.close()
file_name = input('請輸入文件名:')
filewrite(file_name)
運行過程如下:
請輸入文件名:1111.txt
請輸入內(nèi)容【單獨輸入‘:w’保存退出】:
123
123
456
aaa
啊啊啊
:w
Process finished with exit code 0
文件打開查看:
123
123
456
aaa
啊啊啊
1. 編寫一個程序葫掉,比較用戶輸入的兩個文件,如果不同跟狱,顯示出所有不同處的行號與第一個不同字符的位置俭厚,程序?qū)崿F(xiàn)如圖:
(圖片轉(zhuǎn)自https://blog.csdn.net/junwei0206/article/details/44988195)
答:代碼如下:
def file_compare(file1, file2):
f1 = open(file1)
f2 = open(file2)
count = 0 # 統(tǒng)計行數(shù)
differ = [] # 統(tǒng)計不一樣的數(shù)量
for line1 in f1:
line2 = f2.readline()
count += 1
if line1 != line2:
differ.append(count)
f1.close()
f2.close()
return differ
file1 = input('請輸入需要比較的頭一個文件名:')
file2 = input('請輸入需要比較的另一個文件名:')
differ = file_compare(file1, file2)
if len(differ) == 0:
print('兩個文件完全一樣!')
else:
print('兩個文件共有【%d】處不同:' % len(differ))
print(differ)
for each in differ:
print('第%d行不一樣' % each)
輸出:
請輸入需要比較的頭一個文件名:1111.txt
請輸入需要比較的另一個文件名:33.txt
兩個文件共有【5】處不同:
[7, 13, 22, 24, 29]
第7行不一樣
第13行不一樣
第22行不一樣
第24行不一樣
第29行不一樣
2. 編寫一個程序驶臊,當用戶輸入文件名和行數(shù)(N)后挪挤,將該文件的前N行內(nèi)容打印到屏幕上,程序?qū)崿F(xiàn)如圖:
(圖片轉(zhuǎn)自https://blog.csdn.net/junwei0206/article/details/44988195)
答:代碼如下:兩種都可以
def file_print(file, num):
f = open(file)
print('''文件%s的前%d行的內(nèi)容如下:''' % (file, num))
for i in range(num):
print(f.readline())
f.close()
file_name = input('請輸入要打開的文件(C:\\test.txt):')
num = int(input('請輸入需要顯示該文件前幾行:'))
file_print(file_name, num)
def file_view(file_name, line_nun):
print('\n文件%s的前%s的內(nèi)容如下:\n' % (file_name, line_num))
f = open(file_name)
for i in range(int(line_num)):
print(f.readline(), end='')
f.close()
file_name = input(r'請輸入要打開的文件(C:\\test.txt):')
line_num = input('請輸入需要顯示該文件前幾行:')
file_view(file_name, line_num)
3. 呃关翎,不得不說我們的用戶變得越來越刁鉆了扛门。要求在上一題的基礎(chǔ)上擴展,用戶可以隨意輸入需要顯示的行數(shù)纵寝。(如輸入13:21打印第13行到第21行论寨,輸入:21打印前21行,輸入21:則打印從第21行開始到文件結(jié)尾所有內(nèi)容)
(圖片轉(zhuǎn)自https://blog.csdn.net/junwei0206/article/details/44988195)
答:代碼如下:
def file_print(file, paragraph):
(start, end) = paragraph.split(':')
if start == '':
start = 1
else:
start = int(start)
if end == '':
end = -1
else:
end = int(end)
f = open(file)
if start == 1:
if end == -1:
print('''文件%s的從開頭到結(jié)束的內(nèi)容如下:''' % file)
else:
print('''文件%s的從開頭到第%d行的內(nèi)容如下:''' % (file, end))
else:
if end == -1:
print('''文件%s的從%d行到結(jié)束的內(nèi)容如下:''' % (file, start))
else:
print('''文件%s的從第%d行到第%d行的內(nèi)容如下:''' % (file, start, end))
for i in range(start - 1):
f.readline()
num = end - start + 1
if num < 0:
print(f.read())
else:
for i in range(num):
print(f.readline())
f.close()
file_name = input(r'請輸入要打開的文件(C:\\test.txt):')
paragraph = input('請輸入需要顯示的行數(shù)【格式如13:21或:21或21:】:')
while paragraph == '':
paragraph = input('輸入有誤,請重新輸入:')
file_print(file_name, paragraph)
4. 編寫一個程序葬凳,實現(xiàn)“全部替換”功能绰垂。
答:代碼如下:
def file_replace(file_name, rep_word, new_word):
f_read = open(file_name)
content = []
count = 0
for each_line in f_read:
if rep_word in each_line:
count += each_line.count(rep_word) # count感覺應(yīng)該用這個
each_line = each_line.replace(rep_word, new_word)
content.append(each_line)
decide = input('\n文件 %s 中共有%s個【%s】\n您確定要把所有的【%s】替換為【%s】嗎?\n【YES/NO】:' \
% (file_name, count, rep_word, rep_word, new_word))
if decide in ['YES', 'Yes', 'yes']:
f_write = open(file_name, 'w')
f_write.writelines(content)
f_write.close()
f_read.close()
file_name = input('請輸入文件名:')
rep_word = input('請輸入需要替換的單詞或字符:')
new_word = input('請輸入新的單詞或字符:')
file_replace(file_name, rep_word, new_word)
執(zhí)行過程:
請輸入文件名:33.txt
請輸入需要替換的單詞或字符:小丑魚
請輸入新的單詞或字符:小甲魚
文件 33.txt 中共有19個【小丑魚】
您確定要把所有的【小丑魚】替換為【小甲魚】嗎火焰?
【YES/NO】:YES
Process finished with exit code 0
5.請寫下這一節(jié)課你學(xué)習(xí)到的內(nèi)容:格式不限劲装,回憶并復(fù)述是加強記憶的好方式!
- 任務(wù):將文件(record.txt 下面我會用33.txt代替)中的數(shù)據(jù)進行分割并按照以下規(guī)律保存起來:
- 小甲魚的對話單獨保存為boy_*.txt的文件(去掉“小甲魚:”)
- 小客服的對話單獨保存為girl_*.txt的文件(去掉“小客服:”)
- 文件中總共有三段對話,分別保存為boy_1.txt规丽,girl_1.txt称近,boy_2.txt,
girl_2.txt谦疾,boy_3.txt,girl_3.txt共6個文件(提示:文件中的不同對話見已經(jīng)使用“=========”分割)
注意:我下面的環(huán)境是python 3.7 + Mac
代碼如下:
def save_file(boy, girl, count):
file_name_boy = 'boy_' + str(count) + '.txt'
file_name_girl = 'girl_' + str(count) + '.txt'
boy_file = open('%s' % file_name_boy, 'w')
girl_file = open('%s' % file_name_girl, 'w')
boy_file.writelines(boy)
girl_file.writelines(girl)
boy_file.close()
girl_file.close()
def split_file(file_name):
f = open(file_name)
boy = []
girl = []
count = 1
for each_line in f:
if each_line[:6] != '======':
(role, line_spoken) = each_line.split(':', 1)
if role == '小甲魚':
boy.append(line_spoken)
if role == '小客服':
girl.append(line_spoken)
else:
save_file(boy, girl, count)
count += 1
boy = []
girl = []
save_file(boy, girl, count)
f.close()
split_file('33.txt')
需要注意的幾點:
1址否、代碼中的中文字符:
(role,line_spoken) = each_line.split(':',1)
其中餐蔬,冒號應(yīng)該是中文輸入法下的':',否則會報錯
2佑附、直接在record.txt所在目錄下創(chuàng)建.py文件時樊诺,上述代碼中的打開文件操作可以直接用文件名而不需要指明路徑,即可以修改為:
f.open('record.txt')
上述兩個文件不在同一目錄下時音同,則應(yīng)指明路徑词爬。
3、上面這段代碼在Python 3.7下運行老是報錯:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xbf in position 2: invalid start byte
原因大概就是編碼的問題权均,如果你要在mac上運行這個腳本的話顿膨,自己最好重新根據(jù)record.txt自己生成一個另外的文檔,因為小甲魚給的這個文檔的編碼方式或許在mac上不適用叽赊×滴郑可以自己新建一個文件,把record.txt內(nèi)的內(nèi)容復(fù)制過來即可必指。
33.txt [百度云鏈接:https://pan.baidu.com/s/1FRR95vuwtgnywKywuV8uCA]