python英文统计
⑴ python统计各字母个数
一、实现思路
需要统计字符串中每个字母出现的次数;如果字母是第一次出现的话,就把次数置为1,如果字母非第一次出现的话,就需要在原字母已保存次数上加1;仔细思考一下,需要保存字母和出现次数,然后相同字母出现多次的话,需要在原字母保存的次数加1;字典这种数据类型可以实现这种需求。
二、代码实现
2.1 统计字母出现次数
统计字符串每个字母出现次数源码:
def count_each_char(str):
dict = {}
for i in str:
if i not in dict:
dict[i] = 1
else:
dict[i] += 1
return dict
if __name__ == "__main__":
res = count_each_char("abdefdcsdf")
print(res)
简化版统计字符串字母出现次数源码:
dict[i] 表示的是字典中字母对应的value(出现次数)
dict.get(i,0)+1 表示的是从字典获取字母,如果字典中没有查找到对应字母,则将字母i,次数1存入字典
def count_each_char(str):
dict = {}
for i in str:
dict[i]=dict.get(i,0)+1
return dict
运行结果:2.2 按字母出现次数排序
根据字母出现次数倒序排列源码:
def count_each_char_sort_value(str):
dict = {}
for i in str:
dict[i] = dict.get(i, 0) + 1
# sorted 方法会生成一个排序好的容器
# operator.itemgetter(1) 获取字典第一维的数据进行排序
# reverse 表示倒序排列
dict=sorted(dict.items(),key= operator.itemgetter(1),reverse=True)
return dict
if __name__ == "__main__":
res = count_each_char_sort_value("abdefdcsdf")
print(res)
运行结果:
从运行结果可以看出,通过调用sorted方法,已经根据指定的key进行倒序排序了

⑵ python怎么统计一句英语的单词数量并输出
题主你好,
代码及测试截图如下:

说明: 上图红框处的result可不写, 只是为了看一下分隔结果是否正确.
希望可以帮到题主, 欢迎追问.
⑶ 如何用python实现英文短文的双词频统计
data="""Doyouhearthepeoplesing,singingasongofangrymen.Itisthemusicofapeople,whowillnotbeslavesagain,.."""
data=data.replace(',','')
data=data.replace('.','')
ws=data.split()
dic={}#counttwowords
ws2=[]#twowords
foriinrange(len(ws)-1):
ws2.append(ws[i]+""+ws[i+1])
forw2inws2:
ifdic.get(w2)==None:
dic[w2]=1
else:
dic[w2]+=1
dic_first={}#counttwowordsbyfirstword
forw2inws2:
(l,r)=w2.split()
ifdic_first.get(l)==None:
dic_first[l]=1
else:
dic_first[l]+=1
forw2inws2:#output
(l,r)=w2.split()
printw2,dic[w2],dic_first[l],dic[w2]/float(dic_first[l])
⑷ 编写程序,给出英文句子,统计单词个数,python
代码如下:
len(str.split())
其中str代表给出的英文句子。
代码解释:
1. 将句子切分成一个一个的单词。
str.split()是使用空格将英文句子分成一个一个的单词。空格是split方法的默认值,可以自行更改。返回值就是单词列表。
2. 统计单词数量。
前面我们得到了单词的列表,len()方法可以统计列表的长度,这个长度就是单词的个数。
⑸ 如何用python统计一个txt文件中各个单词出现的次数
1、首先,定义一个变量,保存要统计的英文文章。

⑹ Python里,输入一个英文句子,统计并输出单词个数,怎么弄啊
你好,答案如下所示。mydict={}
for i in input("英文句子").split():
if i in mydict:
mydict[i]+=1
else :
mydict[i]=1
for key,value in mydict.items():
print(key,value)

缩进如图所示
希望你能够详细查看。
如果你有不会的,你可以提问
我有时间就会帮你解答。
希望你好好学习。
每一天都过得充实。
