龙空技术网

打工人学Python:(五)统计单词出现的频率

GO语言入门之路 113

前言:

此时姐妹们对“python统计某个字符出现的次数”大约比较珍视,看官们都需要学习一些“python统计某个字符出现的次数”的相关文章。那么小编同时在网络上汇集了一些关于“python统计某个字符出现的次数””的相关知识,希望朋友们能喜欢,我们一起来学习一下吧!

统计单词出现的频率

#!/usr/bin/env python# -*- encoding: utf-8 -*-'''@Purpose :   Word count @File    :   word_count.py@Time    :   2023/02/24 08:52:41@Author  :   Author@Email   :   Email@em.com'''content = '''China is willing to work with Russia to maintain strategic focus, deepen political mutual trust, strengthen strategic coordination, expand practical cooperation and safeguard the legitimate interests of the two countries and play a constructive role in promoting world peace and development, Wang Yi, director of the Office of theForeign Affairs Commission of the Communist Party of China (CPC) Central Committee, said on Wednesday.'''content = content.replace(".", "").replace(",", "")word_list = content.split()count = {}for w in word_list:    count[w] = count.get(w, 0) + 1print(count)

Python的字符串有三种表示方式:普通字符串、原始字符串和长字符串;

1、普通字符串指用单引号(')或双引号(")括起来的字符串。

2、原始字符串 原始字符串是在字符串的第一个引号前加上字母 r(大小写都可以)

3、长字符串,使用三个单引号(''')或三个双引号(""")括起来

str1 = '普通字符串\n1'str2 = "普通字符串\n2"str3 = r'123\n456'str_long = '''使用三个单引号或三个双引号括起来'''print(str1)print(str2)print(str3)print(str_long)
常用的字符串操作1、使用占位符

要想将表达式的计算结果插入字符串中,则需要用到占位符。对于占位符,使用一对大括号({})表示。

2、字符串查找

字符串的find(sub[,start[,end]])方法用于查找子字符串。在索引start到end之间查找子字符串sub,如果找到,则返回最左端位置的索引;如果没有找到,则返回-1。

3、字符串替换

使用str.replace(old,new[,count])进行字符串替换,用new子字符串替换old子字符串;返回值是替换之后的字符串。count参数指定了替换old子字符串的个数,如果count被省略,则替换所有old子字符串。

4、字符串分割

使用str.split(sep=None,maxsplit=-1)方法分割字符串,sep子字符来分割字符串,maxsplit是最

大分割次数,如果maxsplit被省略,则表示不限制分割次数返回字符串列表对象。

更多的字符串方法可以查看文档慢慢研究;

标签: #python统计某个字符出现的次数 #python判断中文字符个数