python练习题(3):文件字符分布,文件独特行数

文件字符分布,文件独特行数


个人学习记录,欢迎改正

文件字符分布

统计附件文件的小写字母a-z的字符分布,即出现a-z字符的数量,并输出结果。‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬

同时请输出文件一共包含的字符数量。‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬

注意输出格式,各元素之间用英文逗号(,)分隔。‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬

答案可能包含a-z共26个字符的分布,如果某个字符没有出现,则不显示,输出顺序a-z顺序。

示例
输出:共999字符,a:11,b:22,c:33,d:44,e:55

f = open("latex.log")
cc = 0
d = {
    
    }
for i in range(26):
    d[chr(ord('a')+i)] = 0
for line in f:
    for c in line:
        d[c] = d.get(c, 0) + 1
        cc += 1
print("共{}字符".format(cc), end="")
for i in range(26):
    if d[chr(ord('a')+i)] != 0:
        print(",{}:{}".format(chr(ord('a')+i), d[chr(ord('a')+i)]), end="")
#使用 ord('a')+i 配合 range()函数 可以遍历一个连续的字符表

文件独特行数

统计附件文件中与其他任何其他行都不同的行的数量,即独特行的数量。

法一(自己做的)

f = open('latex.log','r')
counts = {
    
    }
txt = []
for line in f:
    line = line.replace('\n','')
    txt.append(line) #文件的每行作为一个元素,加入列表txt中
for i in txt:
    counts[i] = counts.get(i, 0) + 1
item = counts.items()
n = 0
for j in item:
    if j[1] == 1:
        n += 1
print('共{}独特行'.format(n))

嵩天老师给的答案
记住:如果需要"去重"功能,请使用集合类型。

ls.remove()可以去掉某一个元素,如果该行是独特行,去掉该元素后将不在集合t中出现。

f = open("latex.log")
ls = f.readlines()
s = set(ls) #记录ls中出现的字符
for i in s:
    ls.remove(i) #去重,现在ls中剩下的都为重复多余字符
t = set(ls) #记录重复的字符
print("共{}独特行".format(len(s)-len(t))) #总共出现的-重复的即为独特的

猜你喜欢

转载自blog.csdn.net/weixin_43429677/article/details/107429749
今日推荐