提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
目录
题目:
用windows“记事本”创建一个文本文件(hamlet.txt),其中每行包含一段英文。试读出文件的全部内容,并判断:
(1)该文本文件有多少行?
(2)文件中以大写字母开头的有多少行?
(3)包含字符最多和最少的分别在第几行?
(4)该文本一共有多少个单词
hamlet.txt文件:(随便输入测试)
代码:
def line():
f = open("hamlet.txt",'r')
lines = f.readlines()
count = len(lines)
print("这文本文件共有:",count,"行")
def search():
f = open("hamlet.txt",'r')
lines = f.readlines()
n = 0
for line in lines:
if line[0].istitle():
n = n + 1
print("文件中以大写字母开头的有",n,"行")
def r():
f = open("hamlet.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,"行")
def total():
f = open("hamlet.txt", 'r')
lines = f.readlines()
num=0
for line in lines:
a = line.split() # 利用split()方法对字符进行切片
num += len(a)
print("文本一共有",num,"个单词")
line()
search()
r()
total()
效果截图:
总结
提示:这里对文章进行总结:
例如:以上就是今天要讲的内容,本文仅仅简单介绍了用windows“记事本”创建一个文本文件(hamlet.txt),其中每行包含一段英文。试读出文件的全部内容,并判断:(1)该文本文件有多少行?(2)文件中以大写字母开头的有多少行?(3)包含字符最多和最少的分别在第几行?(4)该文本一共有多少个单词,的分析。