簡體   English   中英

如何提取關鍵詞后面的詞

[英]How to Extract Words Following a Key Word

我目前正在嘗試在“我們的”之后提取 4 個詞,但也在“小時”和“你的”之后繼續獲取詞。

即)“我的家人會在我們到達后的 2 小時內發送 email。” (欄內文字)

我想要什么:nan(因為沒有“我們的”)

我得到的:當我們到達時(因為小時是“我們的”)

我嘗試了以下代碼,但仍然沒有運氣。

our = 'our\W+(?P<after>(?:\w+\W+){,4})' 
Reviews_C['Review_for_Fam'] =Reviews_C.ReviewText2.str.extract(our, expand=True)

你能幫忙嗎?

謝謝!

我很驚訝地看到正則表達式用於此,因為它有時會導致不必要的復雜性。 這樣的事情能行嗎?

def extract_next_words(sentence):
    # split the sentence into words
    words = sentence.split()
    
    # find the index of "our"
    index = words.index("our")

    # extract the next 4 words
    next_words = words[index+1:index+5]

    # join the words into a string
    return " ".join(next_words)

您需要確保“我們的”具有空間邊界,如下所示:

our = '(^|\s+)our(\s+)?\W+(?P<after>(?:\w+\W+){,4})'

特別是(^|\s+)our(\s+)? 是你需要玩的地方,這個例子只處理空格和句子的開頭,但你可能需要擴展它以包含引號或其他特殊字符。

下面是用於查找字符串中特定“x”字之后的 n 個字的通用代碼。 它還說明了多次出現的“x”以及未出現的情況。

def find_n_word_after_x(in_str, x, n):
    in_str_wrds = in_str.strip().split()
    x = x.strip()
    if x in in_str_wrds:
        out_lst = []
        for i, i_val in enumerate(in_str_wrds):
            if i_val == x:
                if i+n < len(in_str_wrds):
                    out_str = in_str_wrds[i+1:i+1+n]
                    out_lst.append(" ".join(out_str))
        return out_lst
    else:
        return []
str1 = "our w1 w2 w3 w4 w5 w6"
str2 = "our w1 w2 our w3 w4 w5 w6"
str3 = "w1 w2 w3 w4 our w5 w6"
str4 = "w1"

print(find_n_word_after_x(str1, 'our', 4))
print(find_n_word_after_x(str2, 'our', 4))
print(find_n_word_after_x(str3, 'our', 4))
print(find_n_word_after_x(str4, 'our', 4))

生成 Output:

['w1 w2 w3 w4']
['w1 w2 our w3', 'w3 w4 w5 w6']
[]
[]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM