Python文件操作习题篇(下)有哪些学习笔记要点?
- 内容介绍
- 文章标签
- 相关推荐
本文共计491个文字,预计阅读时间需要2分钟。
使用Python编写一个简单的程序,统计文件中数字字符的出现次数,代码如下:
pythonwith open(abc.txt, r) as fp: count=0 for char in fp.read(): if char.isdigit(): count +=1 print(文件中数字字符的数量为:, count)
2.已经建立文本文件abc.txt,编写一个程序,统计并输出文件中元音字母出现的次数
with open("abc.txt","r") as fp: txt=fp.read() txt=list(txt) num=0 b="aeiouAEIOU" for i in txt: if i in b: num+=1 print("元音字母出现的{0}次".format(num))3.data.txt中保存若干行文本。请编写一个程序读取文件中文本,并统计输出文本的有效行数,然后将结果保存到result.txt中。程序代码必须保存到test.py中
codeline=0 with open('data.txt','r',encoding = 'utf-8') as fp: for i in fp.readlines(): if i != '\n': codeline+=1 with open('result.txt','w') as fp: fp.write('有效行数为:{0}行'.format(str(codeline))) fp.close()4.data.txt中保存有n个单词,每个单词一行。请编写一个程序从文件中将单词读出,找到最长的单词,然后将其保存到result.txt中。程序须保存test.py中
x1 = [] x2 = [] with open("data.txt","r") as fp: txt= fp.readlines() for i in range(len(txt)): txt[i] = txt[i].strip() x1.append(len(txt[i])) m = max(x1) for i in range(len(txt)): if len(txt[i]) == m: x2.append(txt[i]) with open("result.txt","w") as fp: if len(x2) == 1: fp.write('The longest word is: {0}'.format(x2[0])) else: a = ','.join(x2) fp.write('The longest words are: {0}'.format(a)) fp.close()本文共计491个文字,预计阅读时间需要2分钟。
使用Python编写一个简单的程序,统计文件中数字字符的出现次数,代码如下:
pythonwith open(abc.txt, r) as fp: count=0 for char in fp.read(): if char.isdigit(): count +=1 print(文件中数字字符的数量为:, count)
2.已经建立文本文件abc.txt,编写一个程序,统计并输出文件中元音字母出现的次数
with open("abc.txt","r") as fp: txt=fp.read() txt=list(txt) num=0 b="aeiouAEIOU" for i in txt: if i in b: num+=1 print("元音字母出现的{0}次".format(num))3.data.txt中保存若干行文本。请编写一个程序读取文件中文本,并统计输出文本的有效行数,然后将结果保存到result.txt中。程序代码必须保存到test.py中
codeline=0 with open('data.txt','r',encoding = 'utf-8') as fp: for i in fp.readlines(): if i != '\n': codeline+=1 with open('result.txt','w') as fp: fp.write('有效行数为:{0}行'.format(str(codeline))) fp.close()4.data.txt中保存有n个单词,每个单词一行。请编写一个程序从文件中将单词读出,找到最长的单词,然后将其保存到result.txt中。程序须保存test.py中
x1 = [] x2 = [] with open("data.txt","r") as fp: txt= fp.readlines() for i in range(len(txt)): txt[i] = txt[i].strip() x1.append(len(txt[i])) m = max(x1) for i in range(len(txt)): if len(txt[i]) == m: x2.append(txt[i]) with open("result.txt","w") as fp: if len(x2) == 1: fp.write('The longest word is: {0}'.format(x2[0])) else: a = ','.join(x2) fp.write('The longest words are: {0}'.format(a)) fp.close()
