1.统计文件中的数字字符数量
曾经建设文本文件abc.txt,编写一个程序,统计并输入文件中数字字符呈现的次数,文本文件这里就不展现了,上面间接开始敲代码

with open("abc.txt","r") as fp:#以只读形式关上文本文件    txt=fp.read()num=0for i in txt:    if i.isdigit():        num+=1print("数字字符呈现了{0}次".format(num))

2.曾经建设文本文件abc.txt,编写一个程序,统计并输入文件中元音字母呈现的次数

with open("abc.txt","r") as fp:            txt=fp.read()            txt=list(txt)num=0b="aeiouAEIOU"for i in txt:            if i in b:                        num+=1print("元音字母呈现的{0}次".format(num))

3.data.txt中保留若干行文本。
请编写一个程序读取文件中文本,并统计输入文本的无效行数,
而后将后果保留到result.txt中。
程序代码必须保留到test.py中

codeline=0with 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()

以上就是本次分享的全部内容,当初想要学习编程的小伙伴欢送关注Python技术大本营,获取更多技能与教程。