如何在熊猫中搜索多个多词短语?

时间:2019-07-29 02:52:57

标签: python pandas

我将一些JSON数据转换为Pandas DataFrame。我正在寻找字符串内容与多词短语列表匹配的所有列。

我正在使用大量的Twitter JSON数据already downloaded for public use(因此,不适用Twitter API)。此JSON转换为Pandas DataFrame。可用的列之一是text,它是推文的正文。一个例子是

We’re kicking off the first portion of a citywide traffic calming project to make residential streets more safe & pedestrian-friendly, next week!

Tuesday, July 30 at 10:30 AM
Nautilus Drive and 42 Street 

我希望能够有一个短语列表phrases = ["We're kicking off", "we're starting", "we're initiating"],并执行类似pd[pd['text'].str.contains(phrases)]]的操作,以确保我可以获得text列中包含其中一个短语的pandas DataFrame行。 。

这可能要求太多,但理想情况下,我也可以匹配类似phrases = ["(We're| we are) kicking off", "(we're | we are) starting", "(we're| we are) initiating"]

1 个答案:

答案 0 :(得分:0)

列出要匹配的关键字或短语,我提出了完全匹配的逻辑,您可以通过更改正则表达式来进行更改。它还将捕获文本捕获了哪些关键字。 这是代码-

for i in range(len(mustkeywords)):
    for index in range(len(text)):
        result = re.search(r'\s*\b'+mustkeywords[i]+r'\W\s*', text[index])

        if result:
            commentlist.append(text[index])
            keywordlist.append(mustkeywords[i])

tempmustkeywordsdf=pd.DataFrame(columns={"Comments"},data=commentlist) #temp df for keywords
tempmustkeywordsdf["Keywords"]=keywordlist #adding keywords column to this df

必填关键字是包含您的短语或关键字的列表 .text是一个字符串,其中包含您要将关键字检入的所有数据/短语。 tempmustkeywordsdf包含匹配的字符串和与之匹配的关键字。 我希望这会有所帮助。