Search code examples
pythonsplitsentence

Sentence splitting (using conjunction and punctuation) Error: "None" in python


I want to split a sentence. When it finds conjunction(and, or, but) and punctuation(','), I want to split them and return the previous part of the sentence. I tried but I faced a problem. I can correctly split them but at the end, I got an extra line and it was "None". Here is my code:

conj =['and','but','or']
punctuation_lst =['.','!',',',':',';','?']
conj= conj+punctuation_lst

txt='i eat rice , food and many things but service is good'


def conj_based_split(txt):
  lst=[]
  a=1
  for word in txt.split():
    if word not in conj:
      lst.append(word)
    elif (word in conj):
      sent=' '.join(lst)
      print(sent)
      lst.clear()
    if (a==len(txt.split())):
      if(len(lst)):
        sent=' '.join(lst)
        print(sent)
    a=a+1

print(conj_based_split(txt))

and output is:

i eat rice
food
many things
service is good
None

When txt is: 'i eat rice, food and many things but service is good', this code can not split this 'i eat rice, food' part. Expected that it gives: 'i eat rice' and 'food'.

Where is the problem in the code? and How can I remove this "None"? Thank You.


Solution

  • Your code works. The problem is:

    You have a function and in this function you print something. When you call the function you print its output too. However this function returns nothing (None). So just change

    print(conj_based_split(txt))
    

    to

    conj_based_split(txt)
    

    Update after update in question:

    Your code is not general. You split the string with whitespaces and you consider commas have whitespace on both sides.

    So if you change your string from

     'i eat rice, food and many things but service is good'
    

    to

     'i eat rice , food and many things but service is good'
    

    it might work. But you might want to change the logic. Because the correct way to write commas is "something, other thing".