使用变量调用函数时的ValueError

ValueError when using a variable to call a function

我正在尝试编写一个简单的脚本,该脚本以一个单词开头,然后不断打印与前面的单词押韵的单词(即 egg、aaberg、mpeg)。它使用 NLTK。然而,虽然 运行 代码我得到一个错误:

Traceback (most recent call last):
   File "C:\Users\myname\Google Drive\Python codes\Rhyming words.py", line 58, in <module>
     word_real = word[randint(0, len(word)-1)]
   File "C:\Python27\lib\random.py", line 242, in randint
     return self.randrange(a, b+1)
   File "C:\Python27\lib\random.py", line 218, in randrange
    raise ValueError, "empty range for randrange() (%d,%d, %d)" % (istart, istop, width)

ValueError: empty range for randrange() (0,0,0)

我已将其缩小到一个功能,主要功能,即 returns 押韵的单词列表。

def rhyme(inp, level):
     entries = nltk.corpus.cmudict.entries()
     syllables = [(word, syl) for word, syl in entries if word == inp]
     rhymes = []
     for (word, syllable) in syllables:
             rhymes += [word for word, pron in entries if pron[-level:] == syllable[-level:]]
     return rhymes

当我押韵时("egg", 1) 它returns 带有一个押韵词列表。没问题吧?但如果我这样做:

x = "egg"
rhyme(x, 1)

我收到上述错误。换句话说,当我使用变量时它会抛出一个错误,我真的不知道为什么。

完整代码:

# -*- coding: cp1252 -*-
import nltk, time, os
from random import randint

###Words###

import urllib2

word_site = "http://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-type=text/plain"

response = urllib2.urlopen(word_site)
txt = response.read()
WORDS = txt.splitlines()

###end WORDS###

def rhyme(inp, level):
     entries = nltk.corpus.cmudict.entries()
     syllables = [(word, syl) for word, syl in entries if word == inp]
     rhymes = []
     for (word, syllable) in syllables:
             rhymes += [word for word, pron in entries if pron[-level:] == syllable[-level:]]
     return rhymes

def text_file(mode):
     if os.path.isfile("words.txt"):
          words = open("words.txt", mode)
     else:
          words = open("words.txt", "w")
     return words

def start_word():
     words = text_file("r")
     if open("words.txt", "r").readlines() == 0:
          return WORDS[randint(0, len(WORDS)-1)]
     else:
          word = words.readlines()[len(words.readlines())-1]
          return word[0:len(word)-2]
     words.close()

def last_word(last_word):
     words = text_file("a")
     words.write(last_word+"\n")
     words.close()



word_start = start_word()

#debug
print word_start, type(word_start)

while True:
     word = rhyme(word_start, 1)
     #debug
     print word

     if (len(word)-1) < 1:
          word_real = word[randint(0, len(word)-1)]

          print word_real
          last_word(word_real)
          word_start = word_real

          time.sleep(0.3)

所有错误的是 < 而不是 > in:

 if (len(word)-1) < 1:
          word_real = word[randint(0, len(word)-1)]

这与是否使用变量无关。问题似乎出在这里:

 if (len(word)-1) < 1:
      word_real = word[randint(0, len(word)-1)]

你只在 len(word)-1) < 1执行这部分代码,即你randint(0, 0)!

您可能只是错误地使用了 < 而不是 >

 if (len(word)-1) > 1:
      word_real = word[randint(0, len(word)-1)]

或更短:

 if word:
      word_real = random.choice(word)

您在这里生成了一个空范围:

if len(word)-1) < 1:
   word_real = word[randint(0, len(word)-1)]

所以只有在 word 中有 零个或一个元素时才调用 randint()。第二个参数将是 0-1,并且 randint(0, -1) 对该函数无效。

您可能打算改用 >= 1。不使用 randint(),而是使用 random.choice() 从列表中随机选择一个元素:

if word:
   word_real = random.choice(word)
如果 word 列表不为空,则

if word 为真。