从斯蒂芬的回答延伸。这是一个声明性的 Python 方法。
听起来您正试图找到您正在寻找的单词和文本中存在的单词的交集。您可以使用设置交集来实现此目的。
https://docs.python.org/3.8/library/stdtypes.html#frozenset.intersection
代码:
text = "today will be a beautiful sunny day"
get_words = "beautiful sunny"
found_words = list(set(text.split(' ')).intersection(set(get_words.split(' '))))
结果:
found_words == ['beautiful', 'sunny']
为了在 pandas 中跨多行使用它,您可以使用 df.assign。这将根据当前列的操作创建一个新列。
https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.assign.html
代码:
get_words = "beautiful sunny"
word_finder_formatter = lambda row: ', '.join(list(set(row['text'].split(' ')).intersection(set(get_words.split(' ')))))
word_counter = lambda row: len(list(set(row['text'].split(' ')).intersection(set(get_words.split(' '))))
df = df.assign(found_words=word_finder_formatter, found_words_count=word_counter)
结果:
text | found_words | found_words_count
----------------------------------------------------------------------------------
today will be a beautiful sunny day | beautiful, sunny day | 2