我有一个关于英语故事的文本。我的工作是计算这个故事中的字母总数(字母表仅从“a”到“z”和“A”到“Z”)。这就是我写的:
def count():
file=open("xxx.txt","r")
for line in file:
我不知道如何键入下一个,因为我只需要字母而不是'空格',而不是“!”,我该如何改进呢?
答案 0 :(得分:0)
简单的方法就是统计所有这些,然后加上你关心的那些(在这种情况下ascii_letters
)
from collections import Counter
from string import ascii_letters
def count():
c = Counter()
with open("xxx.txt","r") as file:
for line in file:
c.update(line)
return sum(v for k, v in c.items() if k in ascii_letters)
另一种简洁的方法是使用正则表达式
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