Python 3.3.3 TypeError:无法隐式地将'NoneType'对象转换为str

时间:2013-12-25 00:15:04

标签: python python-3.x

我一直在尝试用Python 3.3.3编写Mad-Libs Simulator,我一直收到错误:

Traceback (most recent call last):
File "/Users/RuzHayes_Laptop/Desktop/Programming:Design/Programs/Python Mad Libs Program 000.py", line 80, in <module>
templates=[("The"+" "+adj+" "+n+" "+v+" "+adv+pun),(adj+" "+pluralize(n)+' '+(v[:len(v)-1])+" "+adv+pun)]
TypeError: Can't convert 'NoneType' object to str implicitly

在以下代码中:

print("Welcome!")
print("When you would like to try out ")
print("Python Mad Libs Program, Prototype000,")
begin=input("press the enter/return key.")

print()
print()
print("Initializing befuddlement...")
print()

import random
sentenceCap=35
sentenceBottom=25
numOfSentences=random.randint(sentenceBottom,sentenceCap)
caps={"a":"A","b":"B","c":"C","d":"D",'e':'E','f':'F','g':'G','h':'H','i':'I','j':'J','k':'K','l':'L','m':'M','n':'N','o':'O','p':'P','q':'Q','r':'R','s':'S','t':'T','u':'U','v':'V','w':'W','x':'X','y':'Y','z':'Z'}
tempstore=[" "]*numOfSentences
irregplrls={'child':'children','ox':'oxen','moose':'moose'}
def testforoo(x):
    for j in range(0,len(x)):
        if j+1<=len(x) and x[j:j+1]=='oo'.lower():
            return True
    return False
def pluralize(x):
    l=len(x)
    for i in irregplrls:
        if i == x:
            return irregplrls[x]
    if x[l-1]=="y":
        return x[:l-1]+"ies"
    elif x[l-1]=="s" and x[l-2]=="u":
        return x[:l-2]+"i"
    elif x[l-1] in ('s','x'):
        return x+"es"
    elif x[-2:] in ('ch','sh'):
        return x+"es"
    elif 'f'==x[l-1] or x[l-2]:
        if 'f'==x[l-1]:
            return x[:l-1] + 'ves'
        elif 'f'==x[l-2]:
            return x[:l-2]+"ves"
    elif testforoo(x)!=False:
        return x[:testforoo(x)-2]+'ee'+x[testforoo(x):]
    else:
        return x+'s'

print()
print("Retrieving craploads of words...") 
print()

verb=["moves","jumps", "hides","sniffs","gazes","sneezes","calls"]
noun=["rabbit","dog","cat","otter","seal","elephant","fox",'baby','moose','octopus']
adjec=["happy","angry","cute","enormous","elegant","annoying"]
adver=["merrily","frustratedly","incoherently","morosely","peppily",'exuberantly']
endpunct=[".","!"]



print()
print("Simulating human grammar-speak...")
print()
print()

for i000 in range(0,numOfSentences):
    v=random.choice(verb)
    n=random.choice(noun)
    adj=random.choice(adjec)
    adv=random.choice(adver)
    pun=random.choice(endpunct)
    askinput=random.randint(0,round(numOfSentences/5))
    whichinput=random.randint(0,3)
    if askinput==0:
        if whichinput==0:
            n=input("Please input a noun. ")
        elif whichinput==1:
            v=input("Please input a verb. ")
        elif whichinput==2:
            adj=input("Please input an adjective. ")
        elif whichinput==3:
            adv=input("Please input an adverb. ")
    templates=[("The"+" "+adj+" "+n+" "+v+" "+adv+pun),(adj+" "+pluralize(n)+' '+(v[:len(v)-1])+" "+adv+pun)]
    final=templates[random.randint(0,len(templates)-1)]
    if final[:1]==final[:1].lower():
           final=caps[final[:1]]+final[1:]
    tempstore[i000]=final

print()
print()
print("Producing proof of illiteracy...")
print()
print()

for i001 in range(0,len(tempstore)):
    sent=tempstore[i001]
    print(sent)

我很困惑,我需要帮助。我现在发现问题出现在复数定义的最后,但是我很困惑。该程序一直有效,直到我改变复数以解释某些名词没有被正确复数化。

我将非常感谢您能给我的任何帮助。我现在只编程了大约一个月,这是我尝试过的最难的程序。

谢谢你,圣诞快乐!当然,如果你庆祝圣诞节。

2 个答案:

答案 0 :(得分:0)

如果未正确分配nvadjadv中的一个或多个,则其值为None。您的错误所在的行是将字符串连接在一起,但如果其中一个变量不是字符串,则会抛出您看到的错误。

尝试在不同位置打印这些变量的值,直到您可以准确找到其分配问题的位置。

答案 1 :(得分:0)

def testforoo(x):
    for j in range(0,len(x)):
        if j+1<=len(x) and x[j:j+1]=='oo'.lower():
            return True
    return False

def testforoo(x):
    for j in range(0,len(x)):
        if x[j]=='oo'.lower():
            return True
    return False

因为如果len(x)为4,则j从0到3,j+1从1到4,然后j+1始终&lt; = len(x)

它也是

def testforoo(x):
    return any(x[j]=='oo'.lower() for j in range(0,len(x)))

错误的原因是当pluralize(n)返回None时(我不知道在哪种情况下),可以处理向字符串添加None

如果您使用%s(或使用format)格式,则不会再出现问题。

我在某些地方改进了你的代码。参见:

begin=input("Welcome!\n"
            "When you would like to try out\n"
            "Python Mad Libs Program, Prototype000,"
            "press the enter/return key.")

print("\nInitializing befuddlement...")

import random
sentenceCap=35
sentenceBottom=25
numOfSentences=random.randint(sentenceBottom,sentenceCap)

tempstore=[" "]*numOfSentences
irregplrls={'child':'children','ox':'oxen','moose':'moose'}

def testforoo(x):
    return any(x[j]=='oo'.lower() for j in range(0,len(x)))

def pluralize(x):
    if x in irregplrls:
        return irregplrls[x]

    if x[-1]=="y":
        return x[:-1]+"ies"
    elif x[-2:]=="us":
        return x[:-2]+"i"
    elif x[-1] in 'sx':
        return x+"es"
    elif x[-2:] in ('ch','sh'):
        return x+"es"
    elif 'f'==x[-1] or x[-2]:
        if 'f'==x[-1]:
            return x[:-1] + 'ves'
        elif 'f'==x[-2]:
            return x[:-2]+"ves"
    elif any(x[j]=='oo'.lower() for j in range(0,len(x))):
        return x[:testforoo(x)-2]+'ee'+x[testforoo(x):]
    else:
        return x+'s'

print("\nRetrieving craploads of words...") 

verb=["moves","jumps", "hides","sniffs","gazes","sneezes","calls"]
noun=["rabbit","dog","cat","otter","seal","elephant","fox",'baby','moose','octopus']
adjec=["happy","angry","cute","enormous","elegant","annoying"]
adver=["merrily","frustratedly","incoherently","morosely","peppily",'exuberantly']
endpunct=[".","!"]

print("\nSimulating human grammar-speak...\n")

for i000 in range(0,numOfSentences):
    v=random.choice(verb)
    n=random.choice(noun)
    adj=random.choice(adjec)
    adv=random.choice(adver)
    pun=random.choice(endpunct)
    askinput=random.randint(0,round(numOfSentences/5))
    whichinput=random.randint(0,3)
    if askinput==0:
        if whichinput==0:
            n=input("Please input a noun. ")
        elif whichinput==1:
            v=input("Please input a verb. ")
        elif whichinput==2:
            adj=input("Please input an adjective. ")
        elif whichinput==3:
            adv=input("Please input an adverb. ")
    templates=["The %s %s %s %s%s" % (adj,n,v,adv,pun),
               "%s %s %s %s%s" % (adj,pluralize(n),v[:len(v)-1],adv,pun)]
    final = random.choice(templates)
    final=final[0].upper() + final[1:]
    tempstore[i000]=final
    print('numOfSentences==',numOfSentences,i000)

print("\nProducing proof of illiteracy...\n")

print ('\n'.join(tempstore))

我不确定pluralize()函数的作用,我让函数testforoo()并没有尝试修改这部分,仔细检查,指令elif 'f'==x[-1] or x[-2]:似乎我怀疑,在我看来一定是elif 'f'==x[-1] or 'f'==x[-2]: