有一个txt文件,里面有许多单词,如图,要求输入一个单词,查询在文件里面出现了几次,并且根据给定的标准给单词“打分”
scores = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2, "f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3, "l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1, "r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4, "x": 8, "z": 10}
代码:
import collections scores = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2, "f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3, "l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1, "r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4, "x": 8, "z": 10} file = open('sowpods.txt') lines = file.read().splitlines() file.close() a = input("请输入一个单词:") def tcount(a): t = 0 for i in range(len(a)): # print(scores[a[i]]) t = t + scores[a[i].lower()] return t count = tcount(a) if a in lines: print("YES") m = collections.Counter(lines) print(a + "出现了" + str(m[a]) + "次,分数是:" + str(count)) else: print("NO") print(a + "未出现,分数是:" + str(count))
1、读取文件时如何消除换行
读取文件:
file.read([size]) 从文件中读取指定的字节数,如果为给定或为负则读取所有
file.readline() 读取整行,包括‘ ’字符
file.readlines() 读取所有行并返回列表
去换行符:
基于str的splitlines()方法 file.read().splitlines()
2、统计单词在文件中出现的次数
其实这个可以遍历获得的列表挨个判断是否相等,可是查到collections有直接可以用的方法。