繁体   English   中英

我正在尝试在文本文件中显示小写字母的总数,但是

[英]I'm trying to display the total amount of lower case letters in a text file, but

我已经收到了德古拉小说的文本文件,我想计算其中包含的小写字母的数量。 我执行的代码没有问题,但是可以打印出4297。我不确定我哪里出错了,希望大家在这里指出我的问题。 谢谢!

缩进不一定反映我在文本编辑器中看到的内容

def main():

        book_file = open('dracula.txt', 'r')
        lower_case = sum(map(str.islower, book_file))   

        print (lower_case)  

    book_file.close()
main()

预期:621607结果:4297

遍历文件时,每次迭代都会得到一行作为值。 如果当前代码运行在字符而不是行上,则将是正确的。 当您在较长的字符串(如书中的一行)上调用islower时,如果字符串中的所有字母均为小写字母,则仅返回True

在您的Dracula副本中,显然有4297行不包含大写字母,所以这就是您得到的结果。 更大的数字是字符数。

您可以通过添加一个额外的步骤来将代码作为单个大字符串读取并对其进行迭代来修复代码。

def main():
    with open('dracula.txt', 'r') as book_file:
        text = book_file.read()
    lower_case = sum(map(str.islower, text))
    print(lower_case) 

我还通过使用with语句来处理关闭文件来稍微修改了您的代码。 这样做很好,因为它会在退出预期的块时始终关闭文件,即使出现了问题并且引发了异常。

您可以使用正则表达式来计算小写和大写字符

import re

text = "sdfsdfdTTsdHSksdsklUHD"

lowercase = len(re.findall("[a-z]", text))
uppercase = len(re.findall("[A-Z]", text))

print(lowercase)
print(uppercase)

输出:

15 
7

您将需要更改读取文件的方式

text = open("dracula.txt").read()
with open('dracula.txt', 'r') as book_file:
   count=0 
   for line in book_file: # for each line in the file you will count the number # of lower case letters and add it to the variable "count"
      count+=sum(map(str.islower, line))  

print("number of lower case letters = " +int(count))

这是一个使用列表推导而不是map()

它遍历文本中的字符并创建所有小写字符的列表。 该列表的长度是文本中小写字母的数量。

with open('dracula.txt') as f:
    text = f.read()
lowers = [char for char in text if char.islower()]
print(len(lowers))

暂无
暂无

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

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