文件内容:
cry on my shoulder
but if you wanna cry
cry on my shoulder
if you need someone who cares for you
if you are feeling sad your heart gets colder
yes i show you what real love can do
代码实现:
with open('doc.txt') as f:
content = f.read().split()
content1=set(content)
print(content1)
b = {}
for i in content1:
count = 0
for a in content:
if a==i:
count+=1
else:
continue
b[i]=count
print(b)
运行结果:
另一种简单的方法:
with open('doc.txt') as f:
content = f.read().split()
b = {}
for i in content:
if i in b:
b[i]+=1
else:
b[i]=1
import pprint ##换行打印
pprint.pprint(b)
运行结果:
利用第三方模块实现:
from collections import Counter
with open('doc.txt') as f:
content = f.read().split()
count = Counter(content) ###调用Counter函数自动计数并打印
print(count)
运行结果:
Counter模块还可以进行自动排序:
from collections import Counter
with open('doc.txt') as f:
content = f.read().split()
count = Counter(content)
result = count.most_common(5) ###自动排序,并显示前5个
print(result)
运行结果: