当前位置 : 主页 > 编程语言 > python >

Python学习笔记|文件操作习题篇(下)

来源:互联网 收集:自由互联 发布时间:2022-06-15
统计文件中的数字字符数量已经建立文本文件abc.txt,编写一个程序,统计并输出文件中数字字符出现的次数,文本文件这里就不展示了,下面直接开始敲代码with open("abc.txt","r") as fp:#以
  • 统计文件中的数字字符数量已经建立文本文件abc.txt,编写一个程序,统计并输出文件中数字字符出现的次数,文本文件这里就不展示了,下面直接开始敲代码 with open("abc.txt","r") as fp:#以只读方式打开文本文件 txt=fp.read() num=0 for i in txt: if i.isdigit(): num+=1 print("数字字符出现了{0}次".format(num))

  • 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()
    上一篇:08-python中的包与模块
    下一篇:没有了
    网友评论