Python:如何创建一个要求准确字数的函数?

标签 python python-2.7 word-count

这是我到目前为止所拥有的:

import string

所以我让用户写一个 5 个单词的句子,只要求 5 个单词:

def main(sentence = raw_input("Enter a 5 worded sentence: ")):
    if len(words)<5:
        words = string.split(sentence)
        wordCount = len(words)
        print "The total word count is:", wordCount

如果用户输入超过5个单词:

    elif len(words)>5:
        print 'Try again. Word exceeded 5 word limit'

少于5个字:

    else:
        print 'Try again. Too little words!'

它不断声明:

UnboundLocalError: local variable 'words' referenced before assignment

最佳答案

您的问题是您在变量 words 存在之前调用 len(words) 。这是第二个代码块的第二行。

words = []
while len(words) != 5:
  words = raw_input("Enter a 5 worded sentence: ").split()
  if len(words) > 5:
    print 'Try again. Word exceeded 5 word limit'
  elif len(words) < 5:
    print 'Try again. Too little words!'

请注意,在 python 中,默认参数是在函数定义时绑定(bind)的,而不是在函数调用时绑定(bind)的。这意味着您的 raw_input() 将在定义 main 时触发,而不是在调用 main 时触发,这几乎肯定不是您想要的。

关于Python:如何创建一个要求准确字数的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9407005/

相关文章:

python - 为什么os.path.abspath()返回的是cwd+file的路径?

javascript - 如何在 CouchDB/Cloudant 上获取 "fieldcount"(如字数统计)?

Objective-C :-[NSString wordCount]

java - WordCount MapReduce 给出了意外的结果

python - 检测pyglet(python)中的两个同时键

python - 函数集使用什么来检查两个对象是否不同?

python - 如何追加到文件而不是创建同名的新文件

python - 修改 MinimalWordCount 示例以从 BigQuery 读取

python - 为什么 tf.Variable 可迭代但不能迭代

python - 如何使用Python查找文件中的特殊单词?