日志12月30日
程序员文章站
2022-03-15 14:49:37
复习标准库:def word_amount(sentence): split_list = sentence.split() dict_result = {} for word_name in split_list: if word_name not in dict_result.keys(): dict_result[word_name] = 1 else: dict_result[word_name...
复习标准库:
def word_amount(sentence):
split_list = sentence.split()
dict_result = {}
for word_name in split_list:
if word_name not in dict_result.keys():
dict_result[word_name] = 1
else:
dict_result[word_name] += 1
return dict_result
if __name__ == '__main__':
sentence = "I can because i think i can"
dict_result = word_amount(sentence)
print(dict_result)
def read_filedata(file_name):
file_obj = ""
try:
# 需要检测的异常代码片段
file_obj = open(file_name, "r")
result_data = file_obj.read()
except IOError, e:
# 发生“IOError”异常进行处理的代码片段
file_obj = "文件不存在:"+ str(e)
else:
# 没有引发“IOError”异常执行的代码片段,返回读取到的数据
return result_data
finally:
# 不管有没有引发错误都会执行的代码片段,isinstance()用于判断一个数据类型
if isinstance(file_obj, str):
return file_obj
elif isinstance(file_obj, file):
file_obj.close()
else:
return "未知错误,请检查您的代码..."
if __name__ == '__main__':
result = read_filedata("abc.txt")
print(result)
本文地址:https://blog.csdn.net/sbqaqsjb/article/details/111998760