计数特定单词

时间:2019-05-30 22:18:02

标签: python string list function sum

我正在开发一个函数,该函数可以计算列表中恰好有五个字母的单词数(包括不能的收缩)。

我在互联网上搜索了类似的问题,但空手而归。

def word_count(wlist):
    """ This function counts the number of words (including contractions like couldn't) in a list w/ exactly 5
        letters."""
    w = 0
    for word in x:
        w += 1 if len(word) == 5 else 0
    return w

x = ["adsfe", "as", "jkiejjl", "jsengd'e", "jjies"]    
print(word_count(x))

我希望此函数计算带有五个字母的列表中单词的数量(包括无法收缩的单词)。感谢您提供任何反馈意见。

5 个答案:

答案 0 :(得分:1)

>>> def word5(wlist):
...     return len([word for word in wlist if len(word)==5])
...
>>> word5(["adsfe", "as", "jkiejjl", "jseke", "jjies"])
3
>>>

答案 1 :(得分:0)

使用过滤器的另一种方法:

wordlist = ["adsfe", "as", "jkiejjl", "jseke", "jjies"]
len(list(filter(lambda x: len(x)==5, wordlist))) 

答案 2 :(得分:0)

提供的答案不涉及列表理解,以防可能更易于理解。

def word5(wlist):
    cnt=0
    for word in wordList:
        cnt += 1 if len(word) == 5 else 0
    return cnt

答案 3 :(得分:0)

您可以这样做:

w5 = list(map(len,wordlist)).count(5)

答案 4 :(得分:0)

具有较小内存占用空间的紧凑型替代方案:

rfe = RFE(log_reg,n_features)
rfe.fit_transform(X_train,y_train)
X_test = rfe.transform(X_test)
predictions = rfe.predict(X_test)

这也可以,但速度要慢2.5倍:

def word5(wlist, n=5):
    return sum((1 for word in wlist if len(word) == n))
相关问题