ASCII和二叉树

时间:2016-05-24 08:25:36

标签: python ascii binary-tree binary-search-tree

我想编写一个读取输入文件和输出文件的程序,它从输入文件中读取字符(仅由小写字母组成),并将每个字符的ASCII码写为二进制字符串。输出文件。我以前有一个二叉树类,它工作正常,所以我应该构建一个二进制树,其中包含由ASCII代码指定的位置中的每个小写字母。然后,我需要读入另一个输入文件和输出文件,该文件使用我提出的二叉树。它应该读入输入文件中的二进制字符串并将字符串转换回相应的字符序列,然后将字符写入输出文件。我在这里有我的代码,它清除了我的输入文本,并且没有在输出文件中写入任何内容。

from binary_tree import BinaryTree

def asciify(input_filename,output_filename):

    input_file = open(input_filename)
    cnt = input_file.read()
    output_file = open(output_filename,'w')
    for line in cnt:
        for char in line:
            if (ord(char) > 96 and ord(char) < 123) or ord(char) == 32 or ord(char) == 10:  
                asc = ord(char)    
                binary = bin(asc) 
                binary = binary[2:]
                output_file.write(binary)
    input_file.close()
    output_file.close()

def alphabet_binTree():

    tree = BinaryTree()
    for letter in ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ' ', "\n"]:
        tree.add(letter,bin(ord(letter))[2:])       
    return tree

def alphabet_writer(input_filename,output_filename):

    input_file = open(input_filename)
    output_file = open(output_filename,'w')
    tree = alphabet_binTree()
    for line in input_file:
        tmp = ''
        for char in line:
            tmp = tmp + str(char)                       
            if tmp == str(bin(ord('\n'))[2:]):           
                output_file.write(tree.get(tmp))
                tmp = ''                                
            elif tmp == str(bin(ord(' '))[2:]):        
                output_file.write(tree.get(tmp))
                tmp = ''
            elif len(tmp) == 7:                         
                output_file.write(str(tree.get(tmp)))
                tmp = ''
    input_file.close()
    output_file.close()

def main():
try:
    input_filename = input("Enter the input file: ")
    output_filename = input("Enter the output file: ")
    asciify(input_filename,output_filename)
    alphabet_writer(output_filename,input_filename)
except FileNotFoundError:
    print("Input file does not exist.")

0 个答案:

没有答案