需要帮助,创建的代码和累加器不计算文本中的大写字母

2024-07-05 14:45:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要为我的python类创建一个程序,计算文本文件中的单词数。它还需要计算文本文件中有多少大写字符

我已经尝试了我所知道的一切。我用过这本书,也给我的教授发过电子邮件,但他还没有给我回复,我不希望很快得到回复

filename = input("Enter the name of the file you wish to process: ")

upperWord = 0
numWords = 0
with open(filename, 'r') as f:
    for line in f:
        wordsList = line.split()
        numWords += len(wordsList)
    for upperCase in f:
        if upperCase.isupper():
            upperWord += 1

print('The file', filename, 'contains', numWords, 'words of which', upperWord, 'of them are capitalized.')

最后的打印语句将按如下方式打印: '文件sample.txt包含149个单词,其中0个大写' 这个文本文件中应该有49个大写单词。 因此,print语句应按如下方式打印: '文件sample.txt包含149个单词,其中59个大写'


Tags: oftheinforlinefilename单词file
1条回答
网友
1楼 · 发布于 2024-07-05 14:45:46

我不确定你认为for upperCase in f会怎么样

第一个循环for line in f遍历整个文件。循环完成后,文件完成;如果不重置指针,则无法再次对其进行迭代

但是你真正想做的是在每一行中迭代每个单词。因此,您的第二个循环应该嵌套在for循环中,并且应该在您刚刚创建的单词列表上循环:

for line in f:
    wordsList = line.split()
    numWords += len(wordsList)
    for word in wordsList:
        if word.isupper():
            upperWord += 1

(另外,检查一下要求:word.isupper()仅当整个单词都是大写时才会返回true。这就是你需要的吗?或者你需要检查这个词是否只包含大写字母?)

编辑

如果要检查单个大写字母,则需要再次迭代该行:

for line in f:
  wordsList = line.split()
  numWords += len(wordsList)
  for character in line:
    if character.isupper():
      upperWord += 1

相关问题 更多 >