Skip to content

Python 908 單字次數計算

題目說明:

請撰寫一程式,要求使用者輸入檔名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

題目解析

  1. 問題分析:
    - 程式需要讀取一個檔案 read.txt
    - 使用者需要輸入一個數字 n,代表要找出出現次數為 n 的單字
    - 程式需要輸出所有出現次數為 n 的單字,並按單字首字母排序

  2. 解題思路:
    - 先讀取檔案 read.txt 的內容到一個字串變數中
    - 將字串按空白字元分割成單字列表
    - 使用字典記錄每個單字出現的次數
    - 遍歷字典,找出值為 n 的鍵(單字)
    - 將找到的單字排序後輸出

  3. 思考方向:
    - 如何讀取檔案內容到字串變數?
    - 如何將字串按空白分割為單字列表?
    - 如何使用字典記錄單字出現次數?
    - 如何從字典中找出值為 n 的鍵?
    - 如何對單字列表進行排序?

Solution

f_name = input()
f = open(f_name, 'r')
l = []
D = {}
n = eval(input())
for line in f:
  for i in line.split():
    if i in D:
      D[i] += 1
    else:
      D[i] = 1
for j in D:
  if D[j] == n:
    l.append(j)

l.sort()

for result in l:
  print(result)


Last update : 13 novembre 2024
Created : 13 novembre 2024

Comments

Comments