1
1
from __future__ import annotations
2
2
3
- import sys
4
3
import doctest
5
- from typing import Optional , TYPE_CHECKING
4
+ import sys
5
+ from typing import TYPE_CHECKING
6
6
7
7
if TYPE_CHECKING :
8
8
from _typeshed import SupportsWrite
@@ -59,8 +59,8 @@ def parse_file(file_path: str) -> list[Letter]:
59
59
[T:1, h:1, a:1, e:1, i:2, t:2, s:3, :3, .:3]
60
60
"""
61
61
chars : dict [str , Letter ] = {}
62
- with open (file_path , "r" , encoding = "utf8" ) as input_file :
63
- while char := input_file .read (1 ):
62
+ with open (file_path ) as input_file :
63
+ while char := input_file .read (1 ):
64
64
if char not in chars :
65
65
chars [char ] = Letter (char , 1 )
66
66
else :
@@ -159,16 +159,20 @@ def huffman_string(string: str, *, sep: str = " ") -> str:
159
159
return sep .join (letter_bitstrings [char ] for char in string )
160
160
161
161
162
- def huffman (file_path : str , * , sep : str = " " , output_file : 'Optional[SupportsWrite[str]]' = None ) -> None :
162
+ def huffman (
163
+ file_path : str , * , sep : str = " " , output_file : SupportsWrite [str ] | None = None
164
+ ) -> None :
163
165
"""
164
166
Parse the file, Huffman Code it and print the result
165
167
to the given output_file, with each bitstring
166
168
separated by sep parameter
167
- >>> huffman("text_data/text_original.txt")
169
+ >>> huffman("text_data/text_original.txt", sep="_" )
168
170
Huffman Coding of text_data/text_original.txt:
169
- 1000 1001 010 110 111 010 110 111 1010 111 011 1011 110 011 00 00 00
170
- >>> with open("text_data/text_huffman.txt", "w", encoding="utf8") as output_file_in1: huffman("text_data/text_original.txt", sep="", output_file=output_file_in1)
171
- >>> with open("text_data/text_huffman.txt", "r", encoding="utf8") as output_file_out1: print(output_file_out1.read())
171
+ 1000_1001_010_110_111_010_110_111_1010_111_011_1011_110_011_00_00_00_
172
+ >>> with open("text_data/text_huffman.txt", "w") as output_file_in1:
173
+ ... huffman("text_data/text_original.txt", sep="", output_file=output_file_in1)
174
+ >>> with open("text_data/text_huffman.txt") as output_file_out1:
175
+ ... print(output_file_out1.read())
172
176
Huffman Coding of text_data/text_original.txt:
173
177
1000100101011011101011011110101110111011110011000000
174
178
<BLANKLINE>
@@ -179,8 +183,8 @@ def huffman(file_path: str, *, sep: str = " ", output_file: 'Optional[SupportsWr
179
183
k : v for letter in traverse_tree (root ) for k , v in letter .bitstring .items ()
180
184
}
181
185
print (f"Huffman Coding of { file_path } :" , file = output_file )
182
- with open (file_path , "r" , encoding = "utf8" ) as input_file :
183
- while char := input_file .read (1 ):
186
+ with open (file_path ) as input_file :
187
+ while char := input_file .read (1 ):
184
188
print (letter_bitstrings [char ], end = sep , file = output_file )
185
189
print (file = output_file )
186
190
0 commit comments