Python 3.x A计算纯字母字母表的总数

Python 3.x A计算纯字母字母表的总数,python-3.x,Python 3.x,我有一篇关于一个英语故事的短文。我的工作是计算这个故事中的字母总数(字母表仅从“a”到“z”和“a”到“z”)。这就是我写的: def count(): file=open("xxx.txt","r") for line in file: 我不知道下一步怎么打字,因为我只需要字母,不需要空格,不需要“!“,我该如何改进它呢?简单的方法是把它们都数一数,然后把你关心的那些加起来(ascii_字母) 另一种简洁的方法是使用正则表达式 def count(): with open("xxx.

我有一篇关于一个英语故事的短文。我的工作是计算这个故事中的字母总数(字母表仅从“a”到“z”和“a”到“z”)。这就是我写的:

def count():
file=open("xxx.txt","r")
for line in file:

我不知道下一步怎么打字,因为我只需要字母,不需要空格,不需要“!“,我该如何改进它呢?

简单的方法是把它们都数一数,然后把你关心的那些加起来(
ascii_字母

另一种简洁的方法是使用正则表达式

def count():
    with open("xxx.txt","r") as file:
        return len(re.findall('[a-zA-Z]', file.read()))
显然这是家庭作业,老师强加了一些任意的限制。在这里使用
ord
chr
仍然没有任何意义

def count():
    c = 0
    with open("xxx.txt","r") as file:
        for line in file:
            for ch in line:
                if 'a' <= ch <= 'z' or 'A' <= ch <= 'Z':
                    c += 1
    return c
def count():
c=0
打开(“xxx.txt”、“r”)作为文件:
对于文件中的行:
对于ch in行:

如果“a”谢谢你的帮助,但我不能使用它,我的老师允许使用“如果”,并给我们一个提示,使用chr()和ord()逐行选择字符。我知道你的方法很好,但这是我的作业。
def count():
    c = 0
    with open("xxx.txt","r") as file:
        for line in file:
            for ch in line:
                if 'a' <= ch <= 'z' or 'A' <= ch <= 'Z':
                    c += 1
    return c