Python練習題-TQC+(908)-單字次數計算

908-單字次數計算
本題重點五步驟:


1.讀取read.txt的內容,以及檔案中某單字出現的次數-使用open()、read()
2.分割字串-使用split()
3.存入set 陣列-使用set()
4.排序-sorted()
5.如果單字出現了使用者輸入的次數,要把單字印出,計算字串出現幾次-使用count()

 

1. 題目說明:

請開啟PYD908.py檔案,依下列題意進行作答,使輸出值符合題意要求。作答完成請另存新檔為PYA908.py再進行評分。

請注意:資料夾或程式碼中所提供的檔案路徑,不可進行變動,read.txt檔案需為UTF-8編碼格式。

2. 設計說明:

請撰寫一程式,要求使用者輸入檔名read.txt,以及檔案中某單字出現的次數。輸出符合次數的單字,並依單字的第一個字母大小排序。(單字的判斷以空白隔開即可)

3. 輸入輸出:

輸入說明

讀取read.txt的內容,以及檔案中某單字出現的次數

輸出說明

輸出符合次數的單字,並依單字的第一個字母大小排序


輸入輸出範例

範例輸入

read.txt
3

範例輸出

a
is
programming
read.txt 

What is Python language
Python is a widely used high level general purpose interpreted dynamic programming language
Its design philosophy emphasizes code readability and its syntax allows programmers to express concepts in fewer lines of code than possible in languages such as C or Java
Python supports multiple programming paradigms including object oriented imperative and functional programming or procedural styles
It features a dynamic type system and automatic memory management and has a large and comprehensive standard library
The best way we learn anything is by practice and exercise questions We have started this section for those beginner to intermediate who are familiar with Python

參考解答:
fn,num=input(),eval(input())

f=open(fn,'r')
w=f.read()

sp1=w.split()
setsp1=sorted(set(sp1))

for i in setsp1:
  
  if(sp1.count(i) == num):
    print(i,end='\n')

看看效果

 

Yiru@Studio - 關於我 - 意如