简体   繁体   English

输入 ASCII 文本文件 / 将每个字符转换为 Python 中的 ASCII 值

[英]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.我正在尝试创建一个 Python 程序,该程序将 ASCII 文本文件作为输入,然后将每个字符转换为其 ASCII 数值并仅保留它们的奇数结果。 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,到目前为止,我已经设法做到了 go,

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.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打开文件:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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