2 回答

TA貢獻1842條經(jīng)驗 獲得超13個贊
是這樣的嗎?我在你的例子中添加了一個重復的詞(“明亮”)。還添加了n_before和n_after輸入周圍單詞的數(shù)量
import pandas as pd
myseries = pd.Series(["it", 'was', 'a', 'bright', 'bright', 'cold', 'day', 'in', 'april'],
index= [0,1,2,3,4,5,6,7,8])
def phrase(w, n_before=1, n_after=1):
search_words = myseries[myseries == w].index
for index in search_words:
start_index = max(index - n_before, 0)
end_index = min(index + n_after+1, myseries.shape[0])
print(myseries.iloc[start_index: end_index])
phrase("bright", n_before=2, n_after=3)
這給出:
1 was
2 a
3 bright
4 bright
5 cold
6 day
dtype: object
2 a
3 bright
4 bright
5 cold
6 day
7 in
dtype: object

TA貢獻1842條經(jīng)驗 獲得超22個贊
這不是很優(yōu)雅,但您可能需要一些條件來說明出現(xiàn)在短語開頭或結尾的單詞。為了解釋重復的單詞,找到重復單詞的所有實例并循環(huán)遍歷您的打印語句。對于變量myseries,我重復了這個詞cold兩次,所以應該有兩個打印語句
import pandas as pd
myseries = pd.Series(["it", 'was', 'a', 'cold', 'bright', 'cold', 'day', 'in', 'april'],
index= [0,1,2,3,4,5,6,7,8])
def phrase(w):
for i in myseries[myseries == w].index.tolist():
search_word= i
if search_word == 0:
print(myseries[search_word], myseries[i+1])
elif search_word == len(myseries)-1:
print(myseries[i-1], myseries[search_word])
else:
print(myseries[i-1], myseries[search_word], myseries[i+1])
輸出:
>>> myseries
0 it
1 was
2 a
3 cold
4 bright
5 cold
6 day
7 in
8 april
dtype: object
>>> phrase("was")
it was a
>>> phrase("cold")
a cold bright
bright cold day
添加回答
舉報