所以我试着解决这个问题
编写一个程序来读取名为文本.txt并将以下内容打印到 屏幕:
该文件中的字符数
该文件中的字母数
该文件中大写字母的数量
该文件中元音的数量
到目前为止,我已经做到了,但我被困在第二步,这是我目前为止得到的。在
file = open('text.txt', 'r')
lineC = 0
chC = 0
lowC = 0
vowC = 0
capsC = 0
for line in file:
for ch in line:
words = line.split()
lineC += 1
chC += len(ch)
for letters in file:
for ch in line:
print("Charcter Count = " + str(chC))
print("Letter Count = " + str(num))
您可以使用正则表达式来执行此操作。找到所有出现的模式作为列表,然后找到该列表的长度。在
上面的答案使用正则表达式,如果您以前没有使用过正则表达式,那么这些表达式非常有用,值得学习。Bunji的代码也更高效,因为在Python中遍历字符串中的字符相对较慢。在
但是,如果您只想尝试使用Python来实现这一点,请查看下面的代码。有几点:首先,将您的
open()
包装在using
语句中,完成后它将自动调用文件上的close()
。接下来,请注意Python允许您以各种有趣的方式使用in
关键字。任何序列都可以是“in-ed”,包括字符串。如果愿意,可以用自己的字符串替换所有string.xxx
行。在相关问题 更多 >
编程相关推荐