Python 如何在某些关键字之前/之后查找单词?
我使用以下代码计算文档文件中的短语数:Python 如何在某些关键字之前/之后查找单词?,python,regex,Python,Regex,我使用以下代码计算文档文件中的短语数: phrases = ['yellow bananas'] clean_text = " ".join(re.findall(r'\w+(?:-\w+)*', doc)) for phrase in phrases: if phrase in clean_text: if phrase not in list_of_phrases: list_of_phrases[phrase] = clean_text.co
phrases = ['yellow bananas']
clean_text = " ".join(re.findall(r'\w+(?:-\w+)*', doc))
for phrase in phrases:
if phrase in clean_text:
if phrase not in list_of_phrases:
list_of_phrases[phrase] = clean_text.count(phrase)
else:
list_of_phrases[phrase] += clean_text.count(phrase)
问题是,有没有可能在我搜索的关键词之前/之后获得一个、两个、三个等词,而不是整个句子
编辑:
样本文件:
Yellow bananas are nice. I like fruits. Nobody knows how many fruits there are out there. There are yellow bananas and many other fruits. Bananas, apples, oranges, mangos.
Ouput是包含关键字的短语计数,例如,在本例中为“黄色香蕉”,关键字前后有1、2、3等词。请向我们展示您想要的预期输出。还请提供文档样本;你的表情让它看起来像连字号。你好。我编辑了我原来的帖子。