简体   繁体   中英

Input a ASCII text file / Convert every character it to ASCII value in Python

I am totally beginner in programmaing, so please forgive my mistakes.

I am trying to create a Python program which takes as input a ASCII text file, then converts every single character in its ASCII number value and keeps only the odd results of them. Finally, I must visyallize my exports for each character, using * as bars with percentage (See picture) enter image description here .

I have managed to go this far,

f = open(r"c:\python\7_ASCII\Sample.txt", "r")
result = ' '.join((str(ord(x)) for x in f))
print(f)

which gives me the following error:

TypeError: ord() expected a character, but string of length 320 found

I've tried many methods such as list comprehensions but the error insists in appearing.

Any ideas?

You are not reading your text file. To do so you have to use f.read() :

f = open(r"c:\python\7_ASCII\Sample.txt", "r")
my_text = f.read()
print(my_text)

With this you can iterate over your text and apply the logic. However, bear in mind that you can open your files using with :

with open(r"c:\python\7_ASCII\Sample.txt", "r") as reader:
    print(reader.read())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM