Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 正在获取从文件读取的ord()_Python_List_Ord - Fatal编程技术网

Python 正在获取从文件读取的ord()

Python 正在获取从文件读取的ord(),python,list,ord,Python,List,Ord,我的代码所做的是计算一封信出现的次数,并将其计入受尊敬的信。因此,如果A出现两次,它将显示2:A。我的问题是,我希望它从文件中读取,而当ord()尝试读取时,它无法读取。我不知道如何解决这个问题 t=open('lettersTEst.txt','r') tList=[0]*26 aL=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',

我的代码所做的是计算一封信出现的次数,并将其计入受尊敬的信。因此,如果A出现两次,它将显示2:A。我的问题是,我希望它从文件中读取,而当ord()尝试读取时,它无法读取。我不知道如何解决这个问题

t=open('lettersTEst.txt','r')
tList=[0]*26
aL=['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']

idx=0


for char in t:
    ch=ord(char)
    if ch >=65 and ch <= 90:
        pos=int(ch)-65
        tList[pos]+=1

for ele in tList:
    print(idx, ": ", tList[ch])
    idx+=1
t=open('letestest.txt','r')
tList=[0]*26
aL=['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']
idx=0
对于t中的字符:
ch=ord(字符)

如果ch>=65且ch在对文件进行迭代时,会得到行。如果需要字符,还需要在每行上迭代

for line in t:
    for char in line:
        ch = ord(char)
        ...

您需要在文件每行的独立字符上循环,并且可以使用
计数器而不是数组

如果只需要大写字符,则在添加到计数器之前添加
if char.isupper()

范例

>>> from collections import Counter
>>> c = Counter()
>>> with open('lettersTEst.txt') as f:
...     for line in f: 
...         for char in line:
...             c[char] += 1
...
>>> for k,v in c.items():
...     print('{}:{}'.format(k,v))
...
a:2
 :4
e:1
g:1
i:3
h:1
m:1
l:1
n:1
p:1
s:4
r:1
t:2

虽然我更喜欢@JohnKugelman的答案而不是我自己的答案,但我想展示两种交替的方法,在单个for循环中迭代文件的每个字符

第一种是使用第二种形式,即使用可调用(读取一个字符)和sentinel(继续调用函数,直到它返回此值),在这种情况下,我将使用该函数读取一个字节:

import functools

read_a_byte = functools.partial(t.read, 1)
for char in iter(read_a_byte,''):
    ch = ord(char)
    ...
第二个常用于展平二维列表,获取迭代的内容(文件),并在迭代中将每个生成的值(每行)链接在一起

import itertools
char_iterator = itertools.chain.from_iterable(t)
for char in char_iterator:
    ch = ord(char)
    ...
然后,您可以将其中一个传递到
collections.Counter
来构造基本计数器,但它不会遵循与
ord
应用的相同逻辑:

read_a_byte = functools.partial(t.read, 1)
c = collections.Counter(iter(read_a_byte,''))

>>> pprint.pprint(dict(c))
{'a': 8,
 'b': 2,
 'c': 9,
 'd': 4,
 'e': 11,
 ...}

我希望这是一个练习。有许多小写字母不在65-90之间。-格吕恩!(问候!德语)是的,没那么严重。这更多的是期中考试。
open
返回一个文件对象。在文件对象上进行迭代时会得到什么?尝试将
print(char)
添加为
套件的
中的第一行。这与OP尝试做的事情不同,他们只对大写字母进行计数。@Tadhgcdonald Jensen当然。可以添加if语句。因此,我说了一个例子