【问题标题】:Python 3.3.3 TypeError : Can't convert 'NoneType' object to str implicitlyPython 3.3.3 TypeError:无法将“NoneType”对象隐式转换为 str
【发布时间】:2013-12-25 09:33:03
【问题描述】:

我一直在尝试在 Python 3.3.3 中编写一个 Mad-Libs 模拟器,但一直收到错误消息:

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)

我很困惑,我需要帮助。我现在发现问题出在复数定义的末尾,但除此之外我很困惑。该程序一直有效,直到我更改了复数以解释某些名词没有正确复数。

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

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

【问题讨论】:

  • 显然是您尝试插入到None 中的字符串中的对象之一。
  • for i000 in...for i0001...天哪,为什么是这些名字?

标签: python python-3.x


【解决方案1】:
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 总是 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]:

【讨论】:

  • 谢谢,这很有帮助!但是,每次使用复数函数时,它都会打印 None 而不是复数。不过,它不会引发错误。我该如何解决?
  • 要修复它,您应该考虑到我写的内容:指令elif 'f'==x[-1] or x[-2]: 不好。它相当于elif ('f'==x[-1]) or (x[-2]):。关于'f' ==x[-1] 没什么好说的。但是x[-2] 被评估为布尔值;但是在 Python 中,每个非空对象都被评估为 True。因此,当验证elif ('f'==x[-1]) or (x[-2]): 之前没有其他条件时,程序进入此测试并首先评估if 'f' ==x[-1],然后评估elif 'f'==x[-2]。但是,当'f' 既不是最后一个字母也不是倒数第二个字母时,这两个条件都不是...
  • ...已验证。所以程序有,在这种情况下没有return 可以执行。当函数不执行任何 return 语句时,它返回 None。
  • 好的,谢谢!我确信我已经尝试过'f'==x[-1] 或'f'==x[-2]。嗯...
  • 我必须提请您注意我的代码中仍然存在但来自您自己的代码的不一致之处。在testforoo') 函数中,您编写了一个测试x[j:j+1]=='oo'.lower() bur x[j:+1] 描述了一个长度为1 的字符串,也就是说只有一个字符,同时它与两个字符串'oo' 进行比较。您必须纠正这种不一致。
【解决方案2】:

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

尝试将这些变量的值打印在不同的位置,直到您可以准确找到它们的赋值问题所在。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-15
    • 2020-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-31
    • 2012-11-19
    相关资源
    最近更新 更多