检查字符串中的(仅整个)单词

时间:2018-09-12 19:55:25

标签: python string count find

Checkio培训。该任务称为流行词。任务是从给定字符串的列表中搜索单词。

例如:

    var self = this;
    setTimeout(function()
        { if (self.items[index].checked)
                self.selectedContactsCount++; 
              else
                  self.selectedContactsCount--; 
             },
            100);

我的代码如下:

textt="When I was One I had just begun When I was Two I was nearly new"

wwords=['i', 'was', 'three', 'near']

几乎可以正常工作,返回

def popular_words(text: str, words: list) -> dict:
    # your code here

    occurence={}
    text=text.lower()


    for i in words:
        occurence[i]=(text.count(i))

    # incorrectly takes "nearly" as "near"


    print(occurence)
    return(occurence)

popular_words(textt,wwords)

因此将“附近”算作“附近”的一部分。这显然是作者的意图。但是,除了

,我找不到其他方法
{'i': 4, 'was': 3, 'three': 0, 'near': 1} 

我可以寻求帮助吗?请以这个相当幼稚的代码为基础。

1 个答案:

答案 0 :(得分:0)

您的简单解决方案就是:

from collections import Counter

textt="When I was One I had just begun When I was Two I was nearly new".lower()
wwords=['i', 'was', 'three', 'near']

txt = textt.split()

keys = Counter(txt)

for i in wwords:
    print(i + ' : ' + str(keys[i]))