簡體   English   中英

返回 python 中的匹配詞

[英]return matching word in python

我編寫了一個腳本,用於檢查“產品內容”表(“TITLE”列)中的值是否與“關鍵字列表”表、“KEYWORD”列(同一工作簿)中的值匹配。 Compare_title function 返回真或假,這沒關系,但我還需要知道哪些關鍵字匹配,所以不僅是真/假 output,還有被認為是“真匹配”的詞。

Python 腳本如下。

import pandas as pd
import re


file_path ='C:/Users/User/Desktop/data.xlsx'


def get_keyword(file_path):
    """
    Get keywords that are active (based on value in column 'ACTIVE?') from 'KEYWORD' column
    from 'Hidden search' terms sheet and convert it into the list
    """
    df = pd.read_excel(file_path, sheet_name='Keyword list')
    keywords = df['KEYWORD'].to_list()

    return keywords


keyword_list = get_keyword(file_path)


def words(phrase: str) -> [str]:
    """
    Splits string to words by all characters that are not letters or digits (spaces, commas etc.)
    """

    return list(map(lambda x: x.lower(), filter(len, re.split(r'\W', phrase))))


def compare_title(file_path):
    """
    Get title from 'Product content' sheet and compare the values with keyword_list values
    """

    df = pd.read_excel(file_path, sheet_name='Product content')
    df = df.fillna('-')
    title = df['TITLE'].apply(lambda find_kw: any([keyword in words(find_kw) for keyword in keyword_list]))

    return title

在此先感謝您的幫助。

我想這就是你要找的:

title = df['TITLE'].apply(lambda find_kw: [keyword for keyword in keyword_list if keyword in words(find_kw)]))

這意味着compare_title將返回list[str]而不是bool 如果你這樣做if compare_title(...)它仍然像以前一樣工作,因為空列表是虛假的,非空列表是真實的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM