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

2024-03-28 20:56:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我将一些JSON数据转换成一个数据帧。我正在查找字符串内容与多单词短语列表匹配的所有列。你知道吗

我正在处理大量的twitterjson数据already downloaded for public use(因此twitterapi的用法是不适用的)。这个JSON被转换成一个数据帧。可用的列之一是text,它是tweet的主体。一个例子是

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列包含其中一个短语的数据帧行。你知道吗

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


Tags: 数据字符串textrejson列表arepd
1条回答
网友
1楼 · 发布于 2024-03-28 20:56:41

用你想匹配的关键字或短语做一个列表,我已经为完美匹配设置了逻辑,你可以通过改变regex来改变它。它还将捕获捕获文本的关键字。 这是密码-

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

这里的mustkeywords是一个包含短语或关键字的列表 .text是一个字符串,其中包含要将关键字签入的所有数据/短语。 tempmustkeywordsdf包含匹配的字符串和匹配它们的关键字。 我希望这有帮助。你知道吗

相关问题 更多 >