简体   繁体   中英

TypeError: cannot concatenate 'str' and 'NoneType' objects?

I have this large script ( I will post the whole thing if I have to but it is very big) which starts off okay when I run it but it immediatly gives me 'TypeError: cannot concatenate 'str' and 'NoneType' objects' when it comes to this last bit of the code:

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")      

I have searched everywhere but gotten nowhere. It seems to have something to do with: word = ('' + lin) . but no matter what I do I can't fix it. What am I doing wrong?

I'm not sure how I did it but with a bit of fiddling and google I came up with a solution, the corrected code is here (if you're interested):

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")      

Thanks for all the replies, they had me thinking and that's how I fixed it!

You can't concatenate a string and a NoneType object. In your code, it appears your variable lin is not getting assigned the value you think it is. You might try an if block that starts like this:

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

to verify that lin is the correct datatype before printing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM