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

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

我要分句。当它找到连词(and, or, but) 和标点符号(',') 时,我想将它们拆分并return 句子的前一部分。我试过了,但我遇到了一个问题。我可以正确地拆分它们,但最后,我得到了一条额外的线,它是 "None"。这是我的代码:

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

输出为:

i eat rice
food
many things
service is good
None

当txt为:'i eat rice, food and many things but service is good',此代码不能拆分此'i eat rice, food'部分。预期它给出:'i eat rice' 和 'food'.

代码哪里出了问题?以及如何删除这个“None”?谢谢。

您的代码有效。问题是:

你有一个函数,在这个函数中你打印了一些东西。当您调用该函数时,您也会打印它的输出。然而这个函数returns没什么(None)。所以只需更改

print(conj_based_split(txt))

conj_based_split(txt)

问题更新后更新:

你的代码不通用。你用空格分割字符串,你认为逗号两边都有空格。

因此,如果您将字符串从

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

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

它可能会起作用。但是您可能想要更改逻辑。因为逗号的正确写法是"something, other thing".