【问题标题】:How to add the number of words in a list/string to a counter?如何将列表/字符串中的单词数添加到计数器?
【发布时间】:2020-11-05 12:54:35
【问题描述】:

我正在创建一个拼写检查程序,它会从字符串输入或文本文件中返回所有拼写错误的单词。我希望程序将拼写错误的单词数相加,并将其打印为统计数据。

我似乎不知道如何计算列表中的单词数,并将其添加到计数器中。

errorCount = 0

while True:
    try:
        selection = int(input("Would you like to enter a string (1), open a text file (2) or Quit (0) ?"))
        if selection==1:
            String = input("Please enter your string: ")
            dictionaryList = readDictionaryFile(dictionaryFile)
            stringList = readString(String)
            errorList = findErrors(dictionaryList, stringList)
            printErrors(errorList)
            errorCount = errorCount + errorList.count()

【问题讨论】:

  • errorList是什么格式,是字符串列表还是字典
  • 它是一个字符串列表,它的元素是字典列表中没有找到的单词
  • 你可以调用 len(errorList) 这将返回列表中元素的数量
  • 那我可以做errorCount = errorCount + len(errorList)吗?非常感谢
  • 只是为了将来清楚,我把这个放在答案中

标签: python while-loop counter


【解决方案1】:

使用 len(errorList) 将返回列表中元素(错误)的数量

【讨论】:

  • 由于某种原因,当我打印 len(errorList) 时,它没有打印数字:/ 我也删除了 errorCount
  • 打印到屏幕上的内容
  • 当我运行它并输入一个拼写错误的单词时,它会打印“拼写错误的单词是:aksjkasj”而没有其他信息,然后再次返回选择
  • 能否请您发布打印声明
  • 在您的打印语句中没有包含错误列表,或者沿着 print("there were " + len(errorList) ) 行添加第二个打印语句
【解决方案2】:
def printErrors(errorList):
    print ("The incorrectly spelled words are: ")
    for words in errorList:
        print(words)

这是打印语句,对不起

【讨论】:

  • 您对错误列表中的单词所做的操作会告诉您列表中的所有单词,但不会输出它们的数量
猜你喜欢
  • 2013-11-30
  • 2020-10-10
  • 1970-01-01
  • 1970-01-01
  • 2021-08-22
  • 1970-01-01
  • 2023-01-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多