Фон
1) У меня есть следующий код для создания df
import pandas as pd
word_list = ['crayons', 'cars', 'camels']
l = ['there are many different crayons in the bright blue box',
'i like a lot of sports cars because they go really fast',
'the middle east has many camels to ride and have fun']
df = pd.DataFrame(l, columns=['Text'])
df
Text
0 there are many different crayons in the bright blue box
1 i like a lot of sports cars because they go really fast
2 the middle east has many camels to ride and have fun
2) И у меня есть следующий код для создания функции
def find_next_words(row, word_list):
sentence = row[0]
# trigger words are the elements in the word_list
trigger_words = []
next_words = []
last_words = []
for keyword in word_list:
words = sentence.split()
for index in range(0, len(words) - 1):
if words[index] == keyword:
trigger_words.append(keyword)
#get the 3 words that follow trigger word
next_words.append(words[index + 1:index + 4])
#get the 3 words that come before trigger word
#DOES NOT WORK...PRODUCES EMPTY LIST
last_words.append(words[index - 1:index - 4])
return pd.Series([trigger_words, last_words, next_words], index = ['TriggerWords','LastWords', 'NextWords'])
3) Эта функция использует слова из word_list
сверху, чтобы найти 3 слова, которые идут до и после в "trigger_words"
вword_list
4) Затем я использую следующий код
df = df.join(df.apply(lambda x: find_next_words(x, word_list), axis=1))
5) И он выдает следующее df
, которое близко к тому, что я хочу
Text TriggerWords LastWords NextWords
0 there are many different crayons [crayons] [[]] [[in, the, bright]]
1 i like a lot of sports cars [cars] [[]] [[because, they, go]]
2 the middle east has many camels [camels] [[]] [[to, ride, and]]
Проблема
6) Однако столбец LastWords
представляет собой пустой список [[]]
.Я думаю, что проблема в этой строке кода last_words.append(words[index - 1:index - 4])
, взятой из функции find_next_words
сверху.
7) Меня это немного смущает, поскольку в столбце NextWords
используется очень похожий код next_words.append(words[index + 1:index + 4])
, взятый из функции find_next_words
, и он работает.
Вопрос
8) Как мне исправить мой код, чтобы он не создавал пустой список списков [[]]
, и вместо этого он дает мне 3 слова, которые идут перед словами в word_list
?