统计一个字符串中各个字符出现的次数

1.使用python进行字符统计

函数介绍:collections.Counter

Dict subclass for counting hashable items.  Sometimes called a bag or multiset.  Elements are stored as dictionary keys and their counts are stored as dictionary values.


>>> c = Counter('abcdeabcdabcaba') # count elements from a string
>>> c.most_common(3) # three most common elements
[('a', 5), ('b', 4), ('c', 3)]
>>> sorted(c) # list all unique elements
['a', 'b', 'c', 'd', 'e']
>>> ''.join(sorted(c.elements())) # list elements with repetitions
'aaaaabbbbcccdde'
>>> sum(c.values()) # total of all counts
15
>>> c['a']  # count of letter 'a'
5
>>> del c['b'] # remove all 'b'
更多方法可查看文档
import collections

str = input()
counter = collections.Counter(str)
for elem in counter:
    print("{}({})".format(elem,counter[elem]))
aagfagdlkfjmvglk我456地方
a(3)
g(3)
f(2)
d(1)
l(2)
k(2)
j(1)
m(1)
v(1)
我(1)
4(1)
5(1)
6(1)
地(1)
方(1)

2.使用java进行字符统计

import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;

public class Main {
	public static void main(String[] args){
		String s = "aagfagdlkfjmvglk我456地方";
		method(s);
	}
	private static void method(String s) {
		TreeMap<Character,Integer> tm = new TreeMap<Character,Integer>();
		Set<Character> st = tm.keySet();
		char[] c = s.toCharArray();
		for(int i = 0;i<c.length;i++){
			if(!st.contains(c[i])){
				tm.put(c[i], 1);
			}else{
				tm.put(c[i], tm.get(c[i])+1);
			}
		}
		printMapDemo(tm);
	}
	private static void printMapDemo(TreeMap<Character,Integer> tm){
		Set<Character> st = tm.keySet();
		Iterator<Character> ti = st.iterator();
		while(ti.hasNext()){
			char key = ti.next();  
	        System.out.println(key+"("+tm.get(key)+")");
		}
	}
}
4(1)
5(1)
6(1)
a(3)
d(1)
f(2)
g(3)
j(1)
k(2)
l(2)
m(1)
v(1)
地(1)
我(1)
方(1)
运行结果与python相同,而Java中的结果经过TreeMap排序。

HashMap与TreeMap的区别:

HashMap :适用于在Map中插入、删除和定位元素。Treemap:适用于按自然顺序或自定义顺序遍历键(key)。

HashMap通常比TreeMap快一点(树和哈希表的数据结构使然),建议多使用HashMap,在需要排序的Map时候才用TreeMap。

HashMap的结果是没有排序的。TreeMap实现SortMap接口,能够把它保存的记录根据键排序,默认是按键值的升序排序,也可以指定排序的比较器,当用Iterator遍历TreeMap时,得到的记录是排过序的。HashMap里面存入的键值对在取出的时候是随机的,它根据键的HashCode值存储数据,根据键可以直接获取它的值,具有很快的访问速度。在Map中插入、删除和定位元素,HashMap是最好的选择。TreeMap取出来的是排序后的键值对。但如果您要按自然顺序或自定义顺序遍历键,那么TreeMap会更好。

Set函数:

在Java中使用Set,可以方便地将需要的类型以集合类型保存在一个变量中.主要应用在显示列表.Set是一个不包含重复元素的 collection。更确切地讲,set 不包含满足 e1.equals(e2) 的元素对 e1 和 e2,并且最多包含一个 null 元素。(相当于数学中 的集合,性质:确定性、互异性、无序性)




猜你喜欢

转载自blog.csdn.net/css_aaa/article/details/80172841