句子拆分(使用连词和标点符号)错误:python中的“无”

u0sqgete  于 2021-09-29  发布在  Java
关注(0)|答案(1)|浏览(271)

我想分开一句话。当它找到连词(and,or,but)和标点符号(‘,’)时,我想将它们分开并返回句子的前一部分。我试过了,但遇到了一个问题。我可以正确地拆分它们,但在最后,我得到了一个额外的行,它是“无”。这是我的密码:

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是:'我吃米饭,食物和很多东西,但服务是好的',这个代码不能分割这个'我吃米饭,食物'的部分。预计它会给出:“我吃米饭”和“食物”。
代码中的问题在哪里?我怎样才能删除这个“无”?非常感谢。

zynd9foi

zynd9foi1#

你的代码可以工作。问题是:
你有一个函数,在这个函数中你可以打印一些东西。调用函数时,也会打印其输出。但是,此函数不返回任何内容(无)。所以只要改变

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

相关问题