【问题标题】:TypeError: cannot concatenate 'str' and 'NoneType' objects?TypeError:无法连接“str”和“NoneType”对象?
【发布时间】:2017-11-21 00:33:35
【问题描述】:

我有这个大脚本(如果需要,我会发布整个内容,但它非常大)当我运行它时它开始正常,但它立即给我'TypeError:无法连接'str'和'NoneType'当谈到代码的最后一点时,对象':

with open("self.txt", "a+") as f:
    f = open("self.txt", "a+")
    text = f.readlines()     
    text_model = markovify.Text(text)
    for i in range(1):
        tool = grammar_check.LanguageTool('en-GB')
        lin = (text_model.make_sentence(tries=800))
        word = ('' + lin)
        matches = tool.check (word)
        correct = grammar_check.correct (word, matches)
        print ">",
        print correct
        print ' '
        f = open("self.txt", "a+")
        f.write(correct + "\n")      

我到处寻找,但一无所获。它似乎与:word = ('' + lin) 有关。但无论我做什么,我都无法修复它。我做错了什么?

【问题讨论】:

  • 您正在尝试连接"string" + "string",其中一个字符串实际上不是字符串而是NoneType,可能是返回的那个一个函数。
  • 看起来text_model.make_sentence() 可以返回None。您要么必须修复 that 函数(因此它总是返回一个字符串),要么在此代码中检查 None
  • Python 回溯显示错误发生的行。
  • 欢迎来到 StackOverflow。请阅读并遵循帮助文档中的发布指南。 Minimal, complete, verifiable example 适用于此。在您发布 MCVE 代码并准确描述问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中并重现您描述的问题。

标签: python string nonetype


【解决方案1】:

我不确定我是怎么做到的,但经过一番摆弄和谷歌我想出了一个解决方案,更正的代码在这里(如果你有兴趣的话):

with open("self.txt", "a+") as f:
                 f = open("self.txt", "a+")
                 text = f.readlines()     
                 text_model = markovify.Text(text)
                for i in range(1):
                  tool = grammar_check.LanguageTool ('en-GB')
                  lin = (text_model.make_sentence(tries=200))
                  matches = tool.check (lin)
                  correct = grammar_check.correct (lin, matches)
                  lowcor = (correct.lower())
                  print ">",
                  print str (lowcor)
                  print ' '
                  f = open("self.txt", "a+")
                  f.write(lowcor + "\n")      

感谢所有回复,他们让我思考,这就是我修复它的方法!

【讨论】:

    【解决方案2】:

    您不能连接字符串和 NoneType 对象。在您的代码中,您的变量 lin 似乎没有被分配您认为的值。你可以试试这样开头的if 块:

    if type(lin) == str: some code else: raise Exception('lin is not the correct datatype')

    在打印之前验证lin 是正确的数据类型。

    【讨论】:

    • 谢谢,这样的工作。它打印了 lin 但 lin 在 if 语句中并没有改变(它是一个马尔可夫链字符串),所以它最终只是打印了同样的东西。我该怎么办?
    • 这基本上就是原始代码所做的。解决根本问题会更好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多