【发布时间】:2022-08-17 19:36:33
【问题描述】:
我得到了一个字符串和该字符串中的一个字符位置。 如果字符位置在单词的中间,我想以不包括最后一个单词的方式获取该位置之前的 n 个单词
text = \'the house is big the house is big the house is big\'
char_nr = 19
list_of_words_before = text[:char_nr-1].split()
print(list_of_words_before) # we see that the string is splited in \"the\" I dont want hence the t in the list
nr_words = 3
if nr_words >len(list_of_words_before):
nr_words = len(list_of_words_before)
list_of_words_before[-nr_words:]
这给出了:
[\'the\', \'house\', \'is\', \'big\', \'t\']
[\'is\', \'big\', \'t\']
但实际上我真正想要的是 [\'house\', \'is\',\'big\'] 因为 t 只是单词的一部分。
你如何确保首先用单词之间的空格来划分? 还有其他解决方案吗?