【问题标题】:How to search for multiple multi-word phrases in pandas?如何在 pandas 中搜索多个多词短语?
【发布时间】:2019-12-06 08:54:51
【问题描述】:

我将一些 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"]之类的东西

【问题讨论】:

  • 请也发布示例数据和预期输出
  • @anky_91 我刚刚更新了!

标签: python pandas


【解决方案1】:

列出您想要匹配的关键字或短语,我已经为完美匹配添加了逻辑,您可以通过更改正则表达式来更改它。它还将捕获文本捕获的关键字。 这是代码-

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 包含匹配的字符串和匹配它们的关键字。 我希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2014-01-10
    • 2012-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 2018-09-03
    相关资源
    最近更新 更多