You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python:使用列表推导式与sum()函数实现单词统计的技术问题

Solution: Word Count Using List Comprehension and sum()

Hey there! Let's build that word_count function exactly as you specified—leaning on list comprehension and sum() even if it's not the most performant method out there. Here's how to do it:

Core Idea

We’ll use a list comprehension to generate a list of values where each element is 1 (or True, which acts like 1 in integer terms) every time we find a match for the target word. Then sum() will add all those up to give us the total count.

The Function Implementation

First, the basic version that splits the string on whitespace and matches exact word strings:

def word_count(string, word):
    # Split the input string into individual words (whitespace-separated)
    split_words = string.split()
    # List comprehension creates a list of 1s for each matching word, sum them up
    return sum([1 for w in split_words if w == word])

We can even simplify this a bit—since boolean values (True/False) are treated as 1 and 0 when summed, we can skip explicitly writing 1 and just use the comparison result:

def word_count(string, word):
    split_words = string.split()
    return sum([w == word for w in split_words])

Applying to the dickens String

Let’s test this with an example dickens string (replace this with your actual text):

# Example Dickens-style string
dickens = "It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness"

# Count how many times "was" appears
was_count = word_count(dickens, "was")
print(was_count)  # Output: 4

Handling Edge Cases (Optional)

If your string has punctuation attached to words (like "times," in the example), you might want to clean the words first to get accurate counts. Here’s how to adjust the function for that:

import string

def word_count(string, word):
    split_words = string.split()
    # Strip punctuation from each word before comparing
    cleaned_words = [word.strip(string.punctuation) for word in split_words]
    return sum([cleaned_word == word for cleaned_word in cleaned_words])

For case-insensitive matching (e.g., counting "It" and "it" as the same word), modify the comparison to use lowercase:

return sum([cleaned_word.lower() == word.lower() for cleaned_word in cleaned_words])

内容的提问来源于stack exchange,提问作者d789w

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:13:13