|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
新手求助,请各位看看这段代码哪里出了问题,运行的时候一直把密后面的一个字也删掉了,字频统计也输不出来
要求:从文件data.txt中读入信息,将其中包含的“密”字(可能出现0次、1次或多次)删除,最后原样输出剩余的文本内容,同时统计出剩余文本中每个汉字出现的次数,并输出。
- f=open('data.txt',encoding='utf-8')
- text=f.read()
- f.close()
- L=list(text)
- for i in L:
- if i=='密':
- L.remove(i)
- else:
- print('%s'%i)
- dic={}
- for j in L:
- if j not in dic:
- dic[j]=1
- else:
- dic[j]+=1
- swd=sort(list(dic.items()),key=lambda lst:lst[1],reverser=True)
- for kword,times in swd:
- print(kword,times)
复制代码
改成这样试试?
- f=open('data.txt',encoding='utf-8')
- text=f.read()
- f.close()
- L=list(text)
- for i in L[:]:
- if i=='密':
- L.remove(i)
- else:
- print('%s'%i)
- dic={}
- for j in L:
- if j not in dic:
- dic[j]=1
- else:
- dic[j]+=1
- swd=sorted(list(dic.items()),key=lambda lst:lst[1],reverse=True)
- for kword,times in swd:
- print(kword,times)
复制代码
|
|