用Windows“記事本”創建一個文本檔案,其中每行包含一段英文。試讀出檔案的全部內容,并判斷:
(1)該文本檔案共有多少行?
(2)檔案中以大寫字母P開頭的有多少行?
(3)一行中包含字符最多的和包含字符最少的分別在第幾行?
如:記事本內容為:
A lot of people today are animal rights advocates.
Some of them are very
Passionate and even quite radical about the issue.
But others argue that “human rights” will always
take priority. In fact, in many places even
the most basic human rights are not adequately
Protected. So why animal rights? What do you
think? And why?
運行結果為: 該文本檔案共有有8行
檔案中以大寫字母P開頭的有2行
包含字符最多的是第1行
包含字符最少的是第8行
uj5u.com熱心網友回復:
def line():f = open("E:\\School\\大三\\Python\\第十一周\\second.txt",'r')
lines = f.readlines()
count = len(lines)
print("這文本檔案共有:",count,"行")
def search():
f = open("2.txt",'r')
lines = f.readlines()
n = 0
for line in lines:
if line[0] == 'T':
n = n + 1
print("檔案中以大寫字母T開頭的有",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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/36236.html
標籤:新技術前沿
上一篇:登錄MySQL資料庫或者用navicat連MySQL出現1045錯誤
下一篇:匯總各類產品第一道工序的總和
