Character frequency

本博客介绍了一个Python函数,用于统计给定文本中字母的频率,并排除数字、空格和标点符号。该函数将字母转换为小写并进行排序,适用于简单替换密码的频率分析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

地址:http://www.codewars.com/kata/53e895e28f9e66a56900011a/train/python


Write a function that takes a piece of text in the form of a string and returns the letter frequency count for the text. This count excludes numbers, spaces and all punctuation marks. Upper and lower case versions of a character are equivalent and the result should all be in lowercase.

The function should return a list of tuples sorted by the most frequent letters first. Letters with the same frequency are ordered alphabetically. 
For example:
 letter_frequency('aaAabb dddDD hhcc')
will return
 [('d',5), ('a',4), ('b',2), ('c',2), ('h',2)]

Letter frequency analysis is often used to analyse simple substitution cipher texts like those created by the Caesar cipher.


代码,注释比较详细:

def letter_frequency(text):
  ans = []
  dic = {}
  #长度计算放在循环里效率低
  lenOfText = len(text)
  
  for i in range(0,lenOfText):
      #提前处理成小写
      alp = text.lower()[i]

      #非字母不统计
      if alp.isalpha() == False:
          continue
        
      #用字典统计字母个数    
      if dic.has_key(alp):
          dic[alp] += 1
      else:
          dic[alp] = 1
  
  #反转字典元素存入list
  for k,v in dic.items():
      ans.append((v,k))
  #按出现频率由高到底排序
  ans.sort(reverse=True)

  #频次相同,按字母序
  lenOfAns = len(ans)
  for i in range(0,lenOfAns-1):
	for j in range(i+1,lenOfAns):
		if ans[i][:1] == ans[j][:1] and ans[i][-1:] > ans[j][-1:]:
			tmp = ans[i]
			ans[i] = ans[j]
			ans[j] = tmp
  #交换字母和频次位置        
  nans = []
  for i in range(0,lenOfAns):
      nans.append((ans[i][1],ans[i][0]))

 return nans


Objectives of this Assignment 1. Declare arrays of different types dynamically. 2. Iterate through arrays, processing all of the elements. 3. Write methods with arrays as parameters and return values In this assignment you will create your own class and write the methods in it. The class you write is called Main and it has four methods that build arrays and four methods that process arrays. All methods should be public and static. Create a project called P7_3 and a class named Main in a file calledMain.java, then follow the instructions below exactly: 1. Write a method named createStrings that takes a String as an input parameter, and returns an array of string with 4 elements. The first element is the original string passed in, the second element is the same string converted to uppercase, the third element is the same string converted to lowercase, and the fourth element is the same string with the first character removed. 2. Write a method called charFrequency that takes an array of strings and a single character as parameters. The method should iterate the array, counting instances of the character passed in. For example, if the array is ["Hello", "There"] and we are asked to count the character 'e', the return value will be three. If the character is not found in any of the elements in the array, the return value should be zero. 3.Add a main method with the usual signature that instantiates the Main class and tests its methods as follow: public static void main(String[] args) { Scanner in = new Scanner(System.in); String str = in.nextLine(); char ch = in.next().charAt(0); // Create arrays String[] stringArray = createStrings(str); // Test processing System.out.println(charFrequency(stringArray, ch)); in.close(); } Input Specification: There are two lines in the input. The first line is the string to be converted. The second line contains one character to be counted. Output Specification: For each case, output the frequency of the specified character in the created array. Sample Input: Hello There e Sample Output: 在这里给出相应的输出。例如: 9
03-10
import java.util.*; class HuffmanNode implements Comparable<HuffmanNode> { int frequency; char data; HuffmanNode left, right; public HuffmanNode(int frequency, char data) { this.frequency = frequency; this.data = data; } public boolean isLeaf() { return left == null && right == null; } @Override public int compareTo(HuffmanNode node) { return frequency - node.frequency; } } public class HuffmanCoding { public static void main(String[] args) { String text = "Hello, world!"; Map<Character, Integer> frequencyMap = buildFrequencyMap(text); HuffmanNode root = buildHuffmanTree(frequencyMap); Map<Character, String> huffmanCodes = buildHuffmanCodes(root); System.out.println("Original text: " + text); System.out.println("Huffman codes: " + huffmanCodes); System.out.println("Encoded text: " + encode(text, huffmanCodes)); System.out.println("Decoded text: " + decode(encode(text, huffmanCodes), root)); } private static Map<Character, Integer> buildFrequencyMap(String text) { Map<Character, Integer> frequencyMap = new HashMap<>(); for (char c : text.toCharArray()) { frequencyMap.put(c, frequencyMap.getOrDefault(c, 0) + 1); } return frequencyMap; } private static HuffmanNode buildHuffmanTree(Map<Character, Integer> frequencyMap) { PriorityQueue<HuffmanNode> priorityQueue = new PriorityQueue<>(); for (Map.Entry<Character, Integer> entry : frequencyMap.entrySet()) { priorityQueue.offer(new HuffmanNode(entry.getValue(), entry.getKey())); } while (priorityQueue.size() > 1) { HuffmanNode left = priorityQueue.poll(); HuffmanNode right = priorityQueue.poll(); HuffmanNode parent = new HuffmanNode(left.frequency + right.frequency, '-'); parent.left = left; parent.right = right; priorityQueue.offer(parent); } return priorityQueue.poll(); } private static Map<Character, String> buildHuffmanCodes(HuffmanNode root) { Map<Character, String> huffmanCodes = new HashMap<>(); buildHuffmanCodesHelper(root, "", huffmanCodes); return huffmanCodes; } private static void buildHuffmanCodesHelper(HuffmanNode node, String code, Map<Character, String> huffmanCodes) { if (node.isLeaf()) { huffmanCodes.put(node.data, code); return; } buildHuffmanCodesHelper(node.left, code + "0", huffmanCodes); buildHuffmanCodesHelper(node.right, code + "1", huffmanCodes); } private static String encode(String text, Map<Character, String> huffmanCodes) { StringBuilder encodedText = new StringBuilder(); for (char c : text.toCharArray()) { encodedText.append(huffmanCodes.get(c)); } return encodedText.toString(); } private static String decode(String encodedText, HuffmanNode root) { StringBuilder decodedText = new StringBuilder(); HuffmanNode current = root; for (char c : encodedText.toCharArray()) { 后面代码请补充完整
07-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值