简体   繁体   English

如何提取关键词后面的词

[英]How to Extract Words Following a Key Word

I'm currently trying to extract 4 words after "our", but keep getting words after "hour" and "your" as well.我目前正在尝试在“我们的”之后提取 4 个词,但也在“小时”和“你的”之后继续获取词。

ie) "my family will send an email in 2 hours when we arrive at."即)“我的家人会在我们到达后的 2 小时内发送 email。” (text in the column) (栏内文字)

What I want: nan (since there is no "our")我想要什么:nan(因为没有“我们的”)

What I get: when we arrive at (because hour as "our" in it)我得到的:当我们到达时(因为小时是“我们的”)

I tried the following code and still have no luck.我尝试了以下代码,但仍然没有运气。

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

Can you please help?你能帮忙吗?

Thank you!谢谢!

Im suprised to see regex used for this due to it causing unneeded complexity sometimes.我很惊讶地看到正则表达式用于此,因为它有时会导致不必要的复杂性。 Could something like this work?这样的事情能行吗?

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)

You need to make sure "our" is with space boundaries, like this:您需要确保“我们的”具有空间边界,如下所示:

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

specifically (^|\s+)our(\s+)?特别是(^|\s+)our(\s+)? is where you need to play, the example only handles spaces and start of sentence, but you might need to extend this to have quotes or other special characters.是你需要玩的地方,这个例子只处理空格和句子的开头,但你可能需要扩展它以包含引号或其他特殊字符。

Here is the generic code for finding the n number of words after a specific 'x' word in the string.下面是用于查找字符串中特定“x”字之后的 n 个字的通用代码。 It also accounts for multiple occurrences of 'x' as well as for non-occurrence.它还说明了多次出现的“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))

Generated Output:生成 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