gpt4 book ai didi

python - 如何评估字典键是否在字符串中

转载 作者:行者123 更新时间:2023-11-30 21:53:00 26 4
gpt4 key购买 nike

我有一个字典dict和一个字符串text。我需要评估字典的键是否出现在字符串中,并打印它们出现的次数。我已经尝试了下面的代码,但错误是:必须是str,而不是dict_keys

for word in text.split():
if text.find(dict.keys()) != -1:
print(word/n)

示例数据:

字典:

{'abandon': -2, 'abandoned': -2, 'abandons': -2, 'abducted': -2, 'abduction': -2}

文字:

"Brenamae_ I WHALE SLAP YOUR FIN AND TELL YOU ONE LAST TIME: GO AWHALE Metin Şentürk Twitterda @metinsenturk MUHTEŞEM ÜÇLÜ; SEN, BEN, MÜZİK RT @byunghns: 😭 I LOVE #틴탑 SO MUCH #쉽지않아 IS GOING TO BE SO GOOD 😭 que hdp maicon lo que le hizo a david luiz jajajajajajajajajajaj,igual se jodio la carrera ドラ"

最佳答案

正如 Python 警告您的那样,dict.keys() 不是字符串,因此您无法调用需要字符串的 .find(dict.keys())作为参数。

您想要的是迭代每个键并分别检查每个键。你现在所做的事情没有多大意义。

您想要执行的操作的正确代码:

I need to evaluate if the keys of the dictionary appear in the string and to print them as many times they appear.

如下:

for k in dict.keys():
if k in text:
for i in range(text.count(k)):
print(k)

这可以优化为仅扫描文本一次,但我会将其留给您。

另外,我强烈建议您不要将您的字典命名为dict,因为这是默认字典类的名称。使用不同的名称。

关于python - 如何评估字典键是否在字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59768830/

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