繁体   English   中英

在python中提取特定字符串之前的2个单词,实际单词和2个字符串?

[英]extracting the 2 words before, the actual word, and the 2 strings after a specific string in python?

我有熊猫系列

       Explanation 

a      "how are you doing today where is she going" 
b      "do you like blueberry ice cream does not make sure " 
c      "this works but you know that the translation is on" 

我想提取字符串“you”前后的2个单词

例如,我希望它像

        Explanation                                                    Explanation Extracted

a      "how are you doing today where is she going"                  "how are you doing today"
b      "do you like blueberry ice cream does not make sure "         do you like blueberry ice 
c      "this works but you know that the translation is on"           "work but you know that"

这个正则表达式给了我“你”之前和之后的两个词,但不包括“你”本身

(?P<before>(?:\w+\W+){,2})you\W+(?P<after>(?:\w+\W+){,2})

如何更改它,以便我可以包含“你”

您可以使用

df['Explanation Extracted'] = df['Explanation'].str.extract(r'\b((?:\w+\W+){0,2}you\b(?:\W+\w+){0,2})', expand=False)

请参阅正则表达式演示

详情

  • \b - 单词边界
  • (?:\w+\W+){0,2} - 零次、一次或两次出现一个或多个单词字符,然后是一个或多个非单词字符
  • you - you的字符串
  • \b - 单词边界
  • (?:\W+\w+){0,2} - 零次、一次或两次出现一个或多个非单词字符,然后是一个或多个单词字符。

熊猫测试:

>>> import pandas as pd
>>> df = pd.DataFrame({'Explanation':["how are you doing today where is she going", "do you like blueberry ice cream does not make sure ", "this works but you know that the translation is on"]})
>>> df['Explanation Extracted'] = df['Explanation'].str.extract(r'\b((?:\w+\W+){0,2}you\b(?:\W+\w+){0,2})', expand=False)
>>> df
                                         Explanation    Explanation Extracted
0         how are you doing today where is she going  how are you doing today
1  do you like blueberry ice cream does not make ...    do you like blueberry
2  this works but you know that the translation i...  works but you know that

我将展示一种没有正则表达式和熊猫的方法,对于这种情况,我认为不需要它。

text1 = "how are you doing today where is she going"
text2 = "do you like blueberry ice cream does not make sure "
text3 = "this works but you know that the translation is on"


def show_trunc_sentence(text, word='you'): # here you can choose another word besides you but you is the default
    word_loc = int(text.split().index('you'))
    num = [word_loc - 2 if word_loc - 2 >= 0 else 0]
    num = int(num[0])
    before = text.split()[num: word_loc + 1]
    after = text.split()[word_loc + 1:word_loc + 3]
    print(" ".join(before + after))


    show_trunc_sentence(text2)

输出: text1 - 你今天过得怎么样 text2 - 你喜欢蓝莓吗 text3 - 有效,但你知道

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM