统计单词个数(忽略大小写)

统计英语儿歌《twinkle twinkle little star》中使用到的单词及出现的次数。

儿歌《twinkle twinkle little star》
Twinkle, twinkle, littlestar,
How I wonder what you are!
Up above the world so high,
Like a diamond in the sky.
Twinkle, twinkle, little star,
How I wonder what you are!
When the blazing sun is gone,
When he nothing shines upon,
Then you show your little light,
Twinkle, twinkle, all the night.
Twinkle, twinkle, little star,
How I wonder what you are!
Then the travler in the dark
Thanks you for your tiny spark;
How could he see where to go,
If you did not twinkle so?
Twinkle, twinkle, little star,
How I wonder what you are!
In the dark blue sky you keep, and
Through my curtains often peep,
For you never shut your eyes,
Till the morning sun does rise.
Twinkle, twinkle, little star,
How I wonder what you are!
As your bright and tiny spark
Lights the travler in the dark,
Though I know not what you are,
Twinkle on, please, little star.
Twinkle, twinkle, little star,
How I wonder what you are!

工具pycharm,利用Python中的的字典

实现代码如下

# 歌词统计
import re

str = "Twinkle, twinkle, littlestar,How I wonder what you are!Up above the world so high,Like a diamond in the sky.Twinkle, twinkle, little star,How I wonder what you are!When the blazing sun is gone,When he nothing shines upon,Then you show your little light,Twinkle, twinkle, all the night.Twinkle, twinkle, little star,How I wonder what you are!Then the travler in the darkThanks you for your tiny spark;How could he see where to go,If you did not twinkle so?Twinkle, twinkle, little star,How I wonder what you are!In the dark blue sky you keep, andThrough my curtains often peep,For you never shut your eyes,Till the morning sun does rise.Twinkle, twinkle, little star,How I wonder what you are!As your bright and tiny sparkLights the travler in the dark,Though I know not what you are,Twinkle on, please, little star.Twinkle, twinkle, little star,How I wonder what you are!"
# 切分字符,并转化成小写
s_list = re.split('[^a-zA-Z]', str.lower())
# 除去空格
r_list = list(filter(None, s_list))
# 定义一个字典
dictionary = {}
for l in r_list:
    count = 0;
    for s in r_list:
        if l == s:
            count = count + 1
    dictionary[l] = count

# 字典按key从大到小排序
sort_list = sorted(dictionary.items(), key=lambda e: e[1], reverse=True)
# 遍历
for s in sort_list:
    print('%s 出现了%d次' % (s[0], s[1]))
<think>好的,我现在需要回答用户关于如何在Python统计单词个数的问题。首先,我要明确用户的需求。他们可能想知道如何统计一个字符串中的单词数量,或者统计文件中每个单词出现的次数。根据常见的需求,可能需要处理这两种情况。 首先,用户可能指的是统计字符串中的单词总数。这通常涉及到分割字符串,比如用split()方法按空格分隔,但需要注意多个空格或标点符号的情况。比如,句子中的标点可能会附着在单词上,比如"Hello, world!"中的"world!”,这时候需要处理标点符号。 其次,用户可能想统计每个单词出现的频率,也就是词频统计。这时候需要将字符串分割成单词列表,然后使用字典或者collections模块中的Counter来统计次数。 另外,还要考虑不同的分割方式,比如是否区分大小写,是否需要过滤停用词(如"the", "a"等),或者如何处理带连字符的单词。不过对于基础问题,可能不需要这么复杂。 接下来,我需要整理几种常见的方法: 1. 使用split()方法分割字符串,统计列表长度。但这种方法简单,可能无法处理多余的空格和标点。 2. 使用正则表达式来更精确地分割单词,比如用re.findall()匹配所有单词。 3. 使用Counter来统计每个单词的出现次数,并展示结果。 可能的步骤是: - 去除标点符号:可以使用字符串的translate方法,或者re.sub替换非字母字符为空格。 - 分割单词:用split()或者正则表达式。 - 统计次数:循环计数,或者用Counter。 需要注意的问题包括大小写处理(比如将单词转为小写统一)、处理撇号(如"don't")和连字符,但可能根据需求不同处理方式不同。对于基础统计,可能先忽略这些复杂情况,假设单词由字母组成,用空格分隔。 然后,我需要编写示例代码,展示不同的方法,并解释每个步骤的作用。例如: 对于统计单词总数: - 使用split()分割,但可能不准确。 - 使用正则表达式分割更准确。 对于统计词频: - 使用字典记录每个单词的出现次数。 - 使用collections.Counter更高效。 同时,可能需要处理文件输入,比如读取文本文件并统计其中的单词。 在回答时,要结构清晰,分点说明,可能包括方法步骤、代码示例、优缺点比较等。还要注意中文解释,避免专业术语过于晦涩。 可能用户的问题比较基础,所以先从简单的方法入手,再介绍更健壮的方法。同时,提醒用户注意潜在的问题,比如标点符号和大小写的影响,并提供相应的处理办法。 最后,确保代码示例正确,语法正确,并给出示例输出,帮助用户理解。</think>在Python统计单词个数通常有两种常见需求:**统计单词数量**和**统计每个单词的出现次数**。以下是分步说明及代码示例: --- ### **一、统计单词数** #### **方法1:基础分割法** **原理**:使用`split()`按空格分割字符串,但无法处理多余空格和标点 ```python text = "Hello world, this is Python!" words = text.split() # 默认按空格分割 word_count = len(words) print("总单词数:", word_count) # 输出:6(标点可能被计入单词,如"world,") ``` #### **方法2:正则表达式法(推荐)** **原理**:使用正则表达式`\b`匹配单词边界,过滤标点 ```python import re text = "Hello world, this is Python!" # 使用正则表达式匹配单词忽略标点) words = re.findall(r'\b\w+\b', text.lower()) # 转小写统一处理 word_count = len(words) print("总单词数:", word_count) # 输出:5("world"被正确提取) ``` --- ### **二、统计每个单词的出现次数** #### **方法1:字典统计法** **原理**:遍历单词列表,使用字典记录频次 ```python text = "apple banana apple orange banana apple" words = text.split() word_freq = {} for word in words: word_freq[word] = word_freq.get(word, 0) + 1 # 存在则+1,否则初始化为0 print("单词频次:", word_freq) # 输出:{'apple': 3, 'banana': 2, 'orange': 1} ``` #### **方法2:`collections.Counter`(高效简洁)** **原理**:直接调用`Counter`统计词频 ```python from collections import Counter text = "apple banana apple orange banana apple" words = text.split() word_freq = Counter(words) print("单词频次:", word_freq) # 输出:Counter({'apple': 3, 'banana': 2, 'orange': 1}) ``` --- ### **三、进阶处理(优化准确性)** #### **场景1忽略大小写和标点** ```python import re from collections import Counter text = "Hello! HELLO, world. World_123" # 正则表达式:匹配字母组成的单词,转小写 words = re.findall(r'\b[a-zA-Z]+\b', text.lower()) word_freq = Counter(words) print("规范化的词频:", word_freq) # 输出:Counter({'hello': 2, 'world': 2}) ``` #### **场景2:从文件中读取文本** ```python import re from collections import Counter # 读取文件内容 with open("example.txt", "r", encoding="utf-8") as file: text = file.read() words = re.findall(r'\b\w+\b', text.lower()) word_freq = Counter(words) print("文件词频统计:", word_freq.most_common(5)) # 输出前5个高频词 ``` --- ### **四、方法对比** | 方法 | 优点 | 缺点 | |--------------------|--------------------------|--------------------------| | `split()` | 简单快速 | 无法处理复杂标点和大小写 | | 正则表达式 | 精准匹配单词 | 需要熟悉正则语法 | | 字典统计 | 灵活可控 | 代码稍长 | | `collections.Counter` | 高效,直接输出统计结果 | 需导入模块 | --- ### **总结** - **简单场景**:直接使用`split()`或`Counter`。 - **复杂文本**:优先使用正则表达式`re.findall()`过滤标点,结合`Counter`统计。 - **文件处理**:读取文件后按相同逻辑处理。 通过上述方法,可以灵活应对不同需求下的单词统计任务。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值