You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于堆排序构建哈夫曼树与编码表及哈夫曼编码树编程练习

Hey there! I've put together a menu-driven Python program that checks both of your boxes. It’s simple to use, handles basic edge cases like missing files, and breaks down each function clearly. Let’s dive in:

def calculate_ascii_frequency(input_filename, output_filename):
    # Initialize a list to count each ASCII character (0-127)
    char_counts = [0] * 128
    total_chars = 0

    try:
        with open(input_filename, 'r', encoding='utf-8') as f:
            for line in f:
                for char in line:
                    ascii_code = ord(char)
                    if 0 <= ascii_code < 128:
                        char_counts[ascii_code] += 1
                        total_chars += 1
    except FileNotFoundError:
        print(f"Error: The file '{input_filename}' was not found.")
        return False

    if total_chars == 0:
        print("Error: No valid ASCII characters found in the input file.")
        return False

    # Calculate relative frequencies (count / total valid chars)
    frequencies = [count / total_chars for count in char_counts]

    # Write frequencies to output file (1 value per line)
    try:
        with open(output_filename, 'w') as f:
            for freq in frequencies:
                f.write(f"{freq:.6f}\n")  # 6 decimal places for consistent precision
        print(f"Success! Frequencies saved to '{output_filename}'.")
        return True
    except Exception as e:
        print(f"Error writing to output file: {e}")
        return False

def load_frequency_file(filename):
    frequencies = {}
    try:
        with open(filename, 'r') as f:
            lines = f.readlines()
            if len(lines) != 128:
                print(f"Error: File must contain exactly 128 lines (found {len(lines)}).")
                return None

            for ascii_code in range(128):
                try:
                    freq = float(lines[ascii_code].strip())
                    frequencies[ascii_code] = freq
                except ValueError:
                    print(f"Error: Invalid number format in line {ascii_code + 1}.")
                    return None

        print("Successfully loaded frequency data!")
        # Print a sample to verify (customize this part as needed)
        print("\nSample frequencies:")
        for code in [32, 48, 65, 97]:  # Space, '0', 'A', 'a'
            print(f"ASCII {code} ('{chr(code)}'): {frequencies[code]:.6f}")
        return frequencies
    except FileNotFoundError:
        print(f"Error: The file '{filename}' was not found.")
        return None
    except Exception as e:
        print(f"Error loading file: {e}")
        return None

def show_menu():
    print("\n=== ASCII Frequency Tool ===")
    print("1. Calculate ASCII character frequencies from a text file")
    print("2. Load ASCII frequencies from a frequency file")
    print("3. Exit")
    choice = input("Enter your choice (1/2/3): ")
    return choice

def main():
    while True:
        choice = show_menu()
        if choice == '1':
            input_file = input("Enter the input text file name: ")
            output_file = input("Enter the output frequency file name: ")
            calculate_ascii_frequency(input_file, output_file)
        elif choice == '2':
            freq_file = input("Enter the frequency file name: ")
            load_frequency_file(freq_file)
        elif choice == '3':
            print("Exiting program. Goodbye!")
            break
        else:
            print("Invalid choice. Please enter 1, 2, or 3.")

if __name__ == "__main__":
    main()

How It Works

  • Menu Navigation: The program starts with a plain-text menu—just type 1, 2, or 3 to pick your task.
  • Function 1: Calculate & Save Frequencies
    • Asks for your input text file, reads through all characters, and counts only valid ASCII characters (0-127).
    • Computes relative frequency for each ASCII code (count divided by total valid characters).
    • Writes results to your chosen output file, with one float value per line (line 1 = ASCII 0, line 2 = ASCII 1, ..., line 128 = ASCII 127).
  • Function 2: Load Frequencies
    • Reads a 128-line frequency file, parses each line into a float.
    • Stores data in a dictionary where keys are ASCII codes and values are their frequencies.
    • Prints a quick sample of loaded data to confirm it worked (you can tweak this to use the data however you need).

Notes

  • Non-ASCII characters in the input text file are ignored (adjust the if 0 <= ascii_code < 128 check if you want to handle them differently).
  • The program includes basic error handling for missing files, invalid number formats, and empty input files.

内容的提问来源于stack exchange,提问作者Rob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:44:14