繁体   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