|
发表于 2020-5-18 08:47:52
From FishC Mobile
|
显示全部楼层
|阅读模式
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
def readFile(fileName):
file = open(fileName,'r')
res = file.read()
return res
def countComments(result):
resList = result.split(',')
commentCnts = {}
for res in resList:
commentCnts[res] = commentCnts.get(res, 0) + 1
return commentCnts
result = readFile("C:\\py\\result.txt")
dicCnts = countComments(result)
file = open("C:\\py\\result.txt",'a')
most=max(dicCnts.values())
for k,v in dicCnts.items():
if v == most:
mostComment = k
break
file.write("根据统计,对今天伙食感觉:\n")
file.write("'很满意'的学生{}人;\n".format(dicCnts["很满意"]))
file.write("'满意'的学生{}人;\n".format(dicCnts["满意"]))
file.write("'一般'的学生{}人;\n".format(dicCnts["一般"]))
file.write("'不满意'的学生{}人。\n".format(dicCnts["不满意"]))
file.write("出现次数最多的评语是{}\n".format(mostComment))
file.close()
result.txt的文件内容:
不满意,一般,很满意,一般,不满意,很满意,满意,一般,一般,不满意,满意,满意,满意,满意,满意,一般,很满意,一般,满意,不满意,满意,一般,不满意,满意,不满意,满意,很满意,很满意,满意,满意,不满意,满意,不满意,满意,一般,很满意,不满意,一般,很满意,满意,很满意,不满意,很满意,不满意,很满意,满意,满意,很满意,一般,很满意,满意,满意,很满意,不满意,很满意,满意,不满意,满意,不满意,满意,很满意,满意,很满意,一般,很满意,很满意,很满意,不满意,满意,一般,一般,一般,一般,不满意,不满意,满意,很满意,很满意,满意,满意,很满意,很满意,一般,一般,很满意,一般,一般,满意,很满意,一般
如何考虑这个文件打开和写入的文件异常处理?
这个是编码问题啊 open() def readFile(fileName):
file = open(fileName,'r',encoding='utf-8')
res = file.read()
file.close()
return res
def countComments(result):
resList = result.split(',')
commentCnts = {}
for res in resList:
commentCnts[zxsq-anti-bbcode-res] = commentCnts.get(res, 0) + 1
return commentCnts
result = readFile("C:\\py\\result.txt")
dicCnts = countComments(result)
print()
file = open("C:\\py\\result.txt",'a',encoding='utf-8')
most=max(dicCnts.values())
for k,v in dicCnts.items():
if v == most:
mostComment = k
break
file.write("\n根据统计,对今天伙食感觉:\n")
file.write("'很满意'的学生{}人;\n".format(dicCnts["很满意"]))
file.write("'满意'的学生{}人;\n".format(dicCnts["满意"]))
file.write("'一般'的学生{}人;\n".format(dicCnts["一般"]))
file.write("'不满意'的学生{}人。\n".format(dicCnts["不满意"]))
file.write("出现次数最多的评语是{}\n".format(mostComment))
file.close()
|
|