当我尝试将此句子压缩为ASCII等效语句时,我不断收到此错误代码TypeError: ord() expected a character, but string of length 5 found
如何修复以下代码
def menu():
print("Compress a file Press 1")
print("Decompress a file Press 2")
print("Quit Press 3")
user_choice = input("")
if user_choice=="1":
compressing()
elif user_choice=="2":
decompressing()
elif user_choice=="3":
import sys
sys.exit()
else:
print("Input invalid.Please enter a number for path selection") , "\n" , menu()
def compressing():
compressed_sentence=[]
sentence=input("Enter a sentence: ")
sentence=sentence.split()
for i in range(len(sentence)):
character=(sentence[i])
ascii_character=ord(character)
compressed_sentence.append(ascii_character)
with open('compressed_file.txt','w') as myFile:
myFile.write(str(compressed_sentence))
menu()
def decompressing():
with open('compressed_file.txt','r') as myFile:
sentence=myFile.read()
for i in sentence:
if i in "[],'":
sentence=sentence.replace(i," ")
new_sentence=sentence.split()
decompressed_sentence=str("")
for i in range(len(new_sentence)):
character=int(new_sentence[i])
decompressed_sentence=(decompressed_sentence+(chr(character)))
final_decompressed_sentence=decompressed_sentence.split()
print(final_decompressed_sentence)
with open('decompressed_file.txt','w') as myFile:
myFile.write(final_decompressed_sentence)
menu()
menu()
为了能够正确压缩和解压缩它。
答案 0 :(得分:2)
没关系,我得到了它的工作:
def menu():
print("Create a file Press 1")
print("Compress a file Press 2")
print("Decompress a file Press 3")
print("Quit Press 4")
user_choice = input("")
if user_choice=="1":
create_a_file()
elif user_choice=="2":
compressing()
elif user_choice=="3":
decompressing()
elif user_choice=="4":
import sys
sys.exit()
else:
print("Input invalid.Please enter a number for path selection") , "\n" , menu()
def create_a_file():
sentence=input("Enter a sentence: ")
sentence=sentence.split()
with open('file.txt','w') as myFile:
myFile.write(str(sentence))
menu()
def compressing():
compressed_sentence=[]
with open('file.txt','r') as myFile:
sentence=myFile.read()
for i in sentence:
if i in "[],'":
sentence=sentence.replace(i," ")
for i in range(len(sentence)):
character=(sentence[i])
ascii_character=ord(character)
compressed_sentence.append(ascii_character)
with open('compressed_file.txt','w') as myFile:
myFile.write(str(compressed_sentence))
menu()
def decompressing():
with open('compressed_file.txt','r') as myFile:
sentence=myFile.read()
for i in sentence:
if i in "[],'":
sentence=sentence.replace(i," ")
new_sentence=sentence.split()
decompressed_sentence=str("")
for i in range(len(new_sentence)):
character=int(new_sentence[i])
decompressed_sentence=(decompressed_sentence+(chr(character)))
final_decompressed_sentence=decompressed_sentence.split()
print(final_decompressed_sentence)
menu()
menu()