获得用户输入,去掉其中全部空格,将其他字符按收入顺序打印输出。
输入 | 输出 |
---|---|
Alice+ Bob | Alice+Bob |
思路:清洗字符串的空格,用replace()方法。
s = input()
s = s.replace(' ', '')
print(s)
关键行指一个文件中包含的不重复行。关键行数指一个文件中包含的不重复行的数量。
统计附件文件中与关键行的数量。
此处仅示例输出格式。
输入 | 输出 |
---|---|
1 | 共99关键行 |
思路:我的思路是,遍历文件,将第一次出现的行全都存到一个set()中,当相同的行第二次出现时(即有重复的)存储到另一个set中,然后用第一个set的长度-第二个set的长度就得到关键行数。
我还试了包括有重复行的行数,也是没有通过。
此外我还尝试了空行计算入内和不计算入内的情况。也都没有通过。
感谢qq_40674586的解答,使得这题有了测试通过的答案。从答案解释,这题就是计算总共有多少行(之后重复的行,不计算在内),空行也要计算入内。
# 版本一
with open('latex.log', 'r', encoding='utf-8') as f:
rows = set()
ex = set()
s = 0
for line in f:
if line not in rows:
rows.add(line)
else:
ex.add(line)
print('共{}关键行'.format(len(rows) - len(ex)))
# 试的另外一种包含重复的行的
with open('latex.log', 'r', encoding='utf-8') as f:
rows = set()
s = 0
for line in f:
if line not in rows:
rows.add(line)
s += 1
print(s)
# 正确答案版本1
with open('latex.log', 'r', encoding='utf-8') as f:
rows = set()
s = 0
for line in f:
if line not in rows:
rows.add(line)
s += 1
print('共{}关键行'.format(s))
# 最简洁的答案
with open('latex.log', 'r', encoding='utf-8') as f:
rows_set = set(f.readlines())
print('共{}关键行'.format(len(rows_set)))
读入一个字典类型的字符串,反转其中键值对输出。
即,读入字典key:value模式,输出value:key模式。
用户输入的字典格式的字符串,如果输入不正确,提示:输入错误。
给定字典d,按照print(d)方式输出。
用户输入的字典格式的字符串,如果输入不正确,提示:输入错误。
输入 | 输出 |
---|---|
{‘a’:1, ‘b’:2} | {1:‘a’, 2:‘b’} |
思路:主要用try…except来控制输入,通过isinstance()方法判断是否是字典,通过zip()来实现key和value互换,注意存在value不可hash的情况,所以需要try…except来监控处理。感谢评论区的小伙伴给出了更简洁的答案。
# 通过测试的版本,这个版本虽然可以通过测试,但是是有问题的,比如输入'abc’就会导致程序报错
s = input()
dict_1 = eval(s)
if isinstance(dict_1, dict):
dict_2 = dict(zip(dict_1.values(), dict_1.keys()))
print(dict_2)
else:
print('输入错误')
# 更推荐这个版本
s = input()
try:
dict_1 = eval(s)
if isinstance(dict_1, dict):
dict_2 = dict(zip(dict_1.values(), dict_1.keys()))
print(dict_2)
else:
print('输入错误')
except:
print('输入错误')
# 更简洁的答案
s = input()
try:
dict_1 = eval(s)
dict_2 = dict(zip(dict_1.values(), dict_1.keys()))
print(dict_2)
except:
print('输入错误')
附件是《沉默的羔羊》中文版内容,请读入内容,分词后输出长度大于2且最多的单词。
如果存在多个单词出现频率一致,请输出按照Unicode排序后最大的单词
文件
字符串
仅提供一个输出示范样例。
输入 | 输出 |
---|---|
无 | 羔羊 |
思路:利用jieba库进行分词,然后主要用到了字典的get方法和列表的sort()方法。不过这题中按照Unicode排序这一步没有做,也通过了测试。评论区有小伙伴给出了解答,所以代码也相应进行了更新。
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
# 对词语根据出现的频率进行排序
wordlst = list(counts.items())
wordlst.sort(key=lambda x:x[1], reverse=True)
maxfreq = wordlst[0][1] # 确定最大的频率
maxfreqwords = [] # 新建一个最大频率单词的列表(假设存在多个单词频率相同,且频率最大)
for i in wordlst:
if i[1] == maxfreq:
maxfreqwords.append(i)
else:
break # 一旦遍历至频率值小于最大频率值时,跳出,不必继续遍历,节约计算时间
maxfreqwords.sort(key=lambda x:x[0], reverse=True) # 按照Unicode排序
print(maxfreqwords[0][0])