Python 如何从短语列表中查找字典中的短语,并使用短语查找和计数创建数据框。重复的应该被计数

Python 如何从短语列表中查找字典中的短语,并使用短语查找和计数创建数据框。重复的应该被计数,python,pandas,dataframe,dictionary,Python,Pandas,Dataframe,Dictionary,如果至少存在匹配项: 预期产出: url phrasecount phrase http://www.firsturl.com 2 going to the market, eating cookies http://www.thirdurl.com 1 i am good 如果所有3个url都不匹配,则只返回第一个出现的url,其计数为零,短语为空

如果至少存在匹配项: 预期产出:

url                             phrasecount    phrase
http://www.firsturl.com         2              going to the market, eating cookies
http://www.thirdurl.com         1              i am good
如果所有3个url都不匹配,则只返回第一个出现的url,其计数为零,短语为空 预期产出:

url                             phrasecount    phrase
http://www.firsturl.com         2              going to the market, eating cookies
http://www.thirdurl.com         1              i am good

从相应的
字典设置初始数据帧
df

url                            phrasecount    phrase
http://www.firsturl.com        0              
处理数据帧:

df = pd.DataFrame({'urls': list(dictionary.keys()), 'strings': list(dictionary.values())})
pattern = '|'.join(phrases)
结果:

s = df.pop('strings').str.findall(pattern)
df = df.assign(phrasecount=s.str.len(), phrase=s.map(', '.join))
df = df.drop_duplicates(subset='phrasecount') if df['phrasecount'].eq(0).all() else df[df['phrasecount'].ne(0)]

短语
列第一行的输出不应该是
走向市场,吃饼干
?当然!那么它是如何工作的呢,这个短语必须准确吗
我是一个好的
并不完美匹配,即使你可以从中拉出
我是好的
?@BerceyEfund正如@sammywemmy所建议的那样,
我是好的
?它是如何包含在输出中的?@ShubhamSharma我认为这只是一个输入错误,因为它与预期的输出不匹配。-->4 pd.DataFrame(dictionary).t.reset_index()获取错误:ValueError:如果使用所有标量值,必须传递index@BerceyEfund好吧,我看到你更新了字典,我必须编辑答案。@BerceyEfund编辑了答案。这是正确的输出。基本上计算列表中的短语在文本中出现的次数。
# print(df)

                      urls  phrasecount                               phrase
0  http://www.firsturl.com            2  going to the market, eating cookies
2  http://www.thirdurl.com            1                            i am good