gpt4 book ai didi

python - 使用列表中的搜索词从文本中获取字数的最快方法?

转载 作者:行者123 更新时间:2023-11-28 22:16:06 25 4
gpt4 key购买 nike

我实际上是在尝试制作一个基本的分类器,所以我可以使用 NLTK 解决方案,但我最初的几次尝试是使用 Pandas。

我有几个列表,我想检查文本并计算字数,然后返回一个有序的

import pandas as pd
import re
fruit_sentences = ["Monday: Yellow makes me happy. So I eat a long, sweet fruit with a peel.",
"Tuesday: A fruit round red fruit with a green leaf a day keeps the doctor away.",
"Wednesday: The stout, sweet green fruit keeps me on my toes!",
"Thursday: Another day with the red round fruit. I like to keep the green leaf.",
"Friday: Long yellow fruit day, peel it and it's ready to go."]
df = pd.DataFrame(fruit_sentences, columns = ['text'])
banana_words = ['yellow', 'long', 'peel']
apple_words = ['round', 'red', 'green leaf']
pear_words = ['stout', 'sweet', 'green']

print(df['text'].str.count(r'[XYZ_word in word list]'))

这里是代码崩溃的地方,因为 str.count() 不接受列表。

最终目标是返回一个像这样的元组列表:

fruits = [('banana', 5), ('pear', 6), ('apple', 6)]

是的,我可以遍历所有列表来执行此操作,但似乎我对 Python 的了解还不够,而不是 Python 不知道如何优雅地处理这个问题。

我发现了这个问题,但看起来每个人都回答错误或使用与实际要求不同的解决方案,这是 here

感谢您帮助这个新手解决问题!

最佳答案

使用str.contains用正则表达式。

# store lists in a dictionary for checking values.
a = {'banana': banana_words, 'apple': apple_words, 'pear':pear_words}

d = {}
# regular expression to match words
regex = '(?<!\S){0}[^\w\s]?(?!\S)'

for i, j in a.items():
d[i] = sum([df['text'].str.contains(regex.format(k), case=False).sum() for k in j])

print (d.items())

输出:

[('banana', 6), ('apple', 6), ('pear', 6)]

关于python - 使用列表中的搜索词从文本中获取字数的最快方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52423333/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com