期末測驗: 課程水平綜合測驗 (第10周)
無空隙回聲輸出
描述
獲得用戶輸入,去掉其中全部空格,將其他字符按收入順序打印輸出。
輸入輸出示例
輸入
Alice + Bob
輸出
Alice+Bob
【我的答案】
s = input()
s = s.replace(' ', '')
print(s)
【參考代碼】
txt = input()
print(txt.replace(" ", ""))
文件關鍵行數
描述
關鍵行指一個文件中包含的不重複行。關鍵行數指一個文件中包含的不重複行的數量。
統計附件文件中與關鍵行的數量。
輸入輸出示例
此處僅示例輸出格式。
輸入 輸出
示例 1
共99關鍵行
【我的答案】
with open('latex.log', 'r', encoding='utf-8') as f:
rows_set = set(f.readlines())
print('共{}關鍵行'.format(len(rows_set)))
【參考代碼】
f = open("latex.log")
ls = f.readlines()
s = set(ls)
print("共{}關鍵行".format(len(s)))
# 記住:如果需要"去重"功能,請使用集合類型。
字典翻轉輸出
描述
讀入一個字典類型的字符串,反轉其中鍵值對輸出。
即,讀入字典key:value模式,輸出value:key模式。
輸入格式
用戶輸入的字典格式的字符串,如果輸入不正確,提示:輸入錯誤。
輸出格式
給定字典d,按照print(d)方式輸出
輸入輸出示例
輸入 輸出
示例 1
{“a”: 1, “b”: 2}
{1: ‘a’, 2: ‘b’}
【我的答案】
s = input()
try:
dict_1 = eval(s)
dict_2 = dict(zip(dict_1.values(), dict_1.keys()))
print(dict_2)
except:
print('輸入錯誤')
【參考代碼】
s = input()
try:
d = eval(s)
e = {}
for k in d:
e[d[k]] = k
print(e)
except:
print("輸入錯誤")
《沉默的羔羊》之最多單詞
描述
附件是《沉默的羔羊》中文版內容,請讀入內容,分詞後輸出長度大於2且最多的單詞。
如果存在多個單詞出現頻率一致,請輸出按照Unicode排序後最大的單詞。
輸入格式
文件
輸出格式
字符串
輸入輸出示例
僅提供一個輸出示範樣例。
輸入 輸出
示例 1
無
羔羊
【我的答案】
import jieba
with open('沉默的羔羊.txt', 'r', encoding='utf-8') as f:
txt = f.read()
words = jieba.lcut(txt)
counts = {}
for word in words:
# 過濾長度爲1的單詞
if len(word) == 1:
continue
else:
counts[word] = counts.get(word, 0) + 1
【參考代碼】
import jieba
f = open("沉默的羔羊.txt")
ls = jieba.lcut(f.read())
# ls = f.read().split()
d = {}
for w in ls:
d[w] = d.get(w, 0) + 1
maxc = 0
maxw = ""
for k in d:
if d[k] > maxc and len(k) > 2:
maxc = d[k]
maxw = k
if d[k] == maxc and len(k) > 2 and k > maxw:
maxw = k
print(maxw)
f.close()