用 Windows “记事本”创建一个文本文件,其中每行包含一段英文,试读出文件的全部内容,并判断:(1)该文本文件共有多少行?(2)文件中以大写字母P开头的有多少行?(3)一行包含字
大学学习之python篇
题目:用 Windows “记事本”创建一个文本文件,其中每行包含一段英文,试读出文件的全部内容,并判断:
(1)该文本文件共有多少行?
(2)文件中以大写字母P开头的有多少行?
(3)一行中包含字符最多的及包含字母最少的分别在第几行?
使用工具:python 3.8
附上个人想法:
(1)创建一个 “Englishe.txt” 文件内容我在百度上寻找作文并加以修改。
(2)按照题目要求完成(1)(2)小问。
(3)第三问用每行遍历字符数的方法得出每行的字符数,并将字符数存入数组当中选取最大数及最小数的下标。
“English.txt”文件内容:
Youth is not a time of life; it is a state of mind; it is not a matter of rosy cheeks, red lips and supple knees; it is a matter of the will, a quality of the imagination.
Youth means a temperamental predominance of courage over timidity.
P years may wrinkle the skin, but to give up enthusiasm wrinkles the soul. Worry, fear, self-distrust bows the hPeart and turns the spirit back to dust.
Whether 60 or 16, there is in every human beings heart the lure of wonders.
When your aerials are down, and your spirit is covered with snows of cynicism and the ice of pessimism.
代码如下:
def line():
f = open("English.txt",'r')
lines = f.readlines()
count = len(lines)
print("这文本文件共有:",count,"行")
def search():
f = open("English.txt",'r')
lines = f.readlines()
n = 0
for line in lines:
if line[0] == 'P':
n = n + 1
print("文件中以大写字母P开头的有",n,"行")
def r():
f = open("English.txt",'r')
lines = f.readlines()
l = []
for i in lines:
num = len(i.strip())
l.append(num)
print("一行中字符最多的在第",l.index(max(l)) + 1,"行")
print("一行中字符最少的在第",l.index(min(l)) + 1,"行")
line()
search()
r()
运行结果:
下一篇: 事件模型