python之单词统计(words count)

本文介绍了一个名为wdCount.py的Python脚本,该脚本用于统计文本中单词出现的次数。通过这个例子,读者可以学习到如何在Python中进行基本的文本处理和计数操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

wdCount.py内容如下:

#!/usr/bin/python
import sys

def print_words(filename):
        fp = open(filename, "r")
        text = fp.read()
        print "text content is :\n" + text
        fp.close()
        split_text = text.split()
        out_list =[]
        out_dict ={}

        for it in split_text:
                if it in out_list:
                        out_dict[it] = 1 + out_dict[it]
                else:
                        out_list.append(it)
                        out_dict[it] = 1
        print '\nprint :'
        #return out_dict
        print out_dict

def main():
        try:
            if len(sys.argv) != 3:
                print 'usage: ./wordcount.py {--count | --topcount} file'
                sys.exit (1)
        except SystemExit:
                print "sys.argv is to less"
        option = sys.argv[1]
        filename = sys.argv[2]
        if option== '--count':
                print_words (filename)
        elif
### Python 实现文件单词统计代码示例 以下是一个完整的 Python 脚本,用于统计指定文本文件中的单词数量。此脚本读取一个文件内容,并对每个单词进行计数,最后输出结果。 ```python import re from collections import Counter def count_words_in_file(file_path): try: with open(file_path, 'r', encoding='utf-8') as file: text = file.read() # 使用正则表达式匹配单词[^2] words = re.findall(r'\b\w+\b', text.lower()) word_count = Counter(words) return word_count except FileNotFoundError: print("文件未找到,请检查路径是否正确。") return None def display_word_count(word_count): if word_count: print("单词统计结果:") for word, count in word_count.most_common(): print(f"{word}: {count}") if __name__ == "__main__": file_path = input("请输入文件路径: ") word_count = count_words_in_file(file_path) display_word_count(word_count) ``` #### 说明 1. **文件读取**:通过 `open` 函数以 UTF-8 编码读取文件内容[^2]。 2. **正则表达式匹配**:使用 `re.findall` 提取所有单词,`\b\w+\b` 是匹配单词的正则表达式,`text.lower()` 确保统计时不区分大小写[^2]。 3. **单词计数**:利用 `collections.Counter` 对提取的单词列表进行计数。 4. **异常处理**:如果文件不存在,程序会提示用户并返回 `None`。 5. **结果展示**:通过 `most_common()` 方法按出现次数排序输出单词及其计数[^2]。 ### 注意事项 - 文件路径需要正确输入,确保文件存在且可访问。 - 文件编码建议为 UTF-8,避免因编码问题导致读取失败。 - 正则表达式 `\b\w+\b` 可根据需求调整,例如支持特殊字符或非英文单词[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值