统计字符串中字母出现的频次,以字典形式呈现。
参考下面的例子,把空白处补充完整。
_______ ______ #导入re库函数
str1='''When I wrote the following pages, or rather the bulk of them, I lived alone, in the woods, a mile from any neighbor,
in a house which I had built myself, on the shore of Walden Pond, in Concord, Massachusetts,
and earned my living by the labor of my hands only.
I lived there two years and two months. At preset I am a sojourner in civilized life again.'''
text=re.____(_____,_____,______) #删除str1中的标点符号
dict1=_______ #定义一个空字典
for each in ______ : #轮询text中的每个字符
if each==' ' or each =='\n': #如果是空格或者换行符,则忽略。
continue
elif each not in dict1.keys():
___________
else:
___________
print(dict1)
import re
str1='''When I wrote the following pages, or rather the bulk of them, I lived alone, in the woods, a mile from any neighbor,
in a house which I had built myself, on the shore of Walden Pond, in Concord, Massachusetts,
and earned my living by the labor of my hands only.
I lived there two years and two months. At preset I am a sojourner in civilized life again.'''
text=re.sub('[.,]' ,' ',str1) #删除str1中的标点符号
# print(text)
dict1= {} #定义一个空字典
for each in text : #轮询text中的每个字符
if each==' ' or each =='\n': #如果是空格或者换行符,则忽略。
continue
elif each not in dict1.keys():
dict1[each] = 1
else:
dict1[each] += 1
print(dict1)
import re
str1='''When I wrote the following pages, or rather the bulk of them, I lived alone, in the woods, a mile from any neighbor,
in a house which I had built myself, on the shore of Walden Pond, in Concord, Massachusetts,
and earned my living by the labor of my hands only.
I lived there two years and two months. At preset I am a sojourner in civilized life again.'''
text=re.sub(r'[,\.]', '',str1, re.DOTALL) #删除str1中的标点符号
dict1= {} #定义一个空字典
for each in text: #轮询text中的每个字符
if each==' ' or each =='\n': #如果是空格或者换行符,则忽略。
continue
elif each not in dict1.keys():
dict1[each] = 1
else:
dict1[each] += 1
print(dict1)
import re #导入re库函数
str1='''When I wrote the following pages, or rather the bulk of them, I lived alone, in the woods, a mile from any neighbor,
in a house which I had built myself, on the shore of Walden Pond, in Concord, Massachusetts,
and earned my living by the labor of my hands only.
I lived there two years and two months. At preset I am a sojourner in civilized life again.'''
text=re.sub(r'[,.]',"",str1) #删除str1中的标点符号
dict1=dict() #定义一个空字典
for each in text : #轮询text中的每个字符
if each==' ' or each =='\n': #如果是空格或者换行符,则忽略。
continue
elif each not in dict1.keys():
dict1[each]=1
else:
dict1[each]+=1
print(dict1)
换种算法可能更好。
1、轮询字符串中非字母字符列表(标点回车和空格)',.: \n' ,用str.replace(char, '')方法去除。
2、利用set()特性获取组成字符串的字母列表。
3、轮询字符串组成字母列表,用str.count(char)方法统计字母出现频次并写入统计频次字典。