【问题标题】:get n words before a character number in a string WITHOUT cut words在字符串中的字符编号之前获取 n 个单词而不使用剪切词
【发布时间】: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 只是单词的一部分。

你如何确保首先用单词之间的空格来划分? 还有其他解决方案吗?

    标签: python string list


    【解决方案1】:

    也许是这样的:

    text = 'the house is big the house is big the house is big'
    char_nr = 19
    list_of_words_before = text[:char_nr - 1]
    if list_of_words_before[-1] != ' ':
        list_of_words_before = list_of_words_before[:-1].split()
    nr_words = 3
    print(list_of_words_before[-nr_words:])
    

    输出:

    ['house', 'is', 'big']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多