Python实用记录(十四):python统计某个单词在TXT/JSON文件中出现的次数

文章目录

代码


import argparse
import ast
import json

def count_word_num_txt(txt_path, word):
    fishing_count = 0
    with open(txt_path, 'r') as file:
        for line in file:
            sentences = ast.literal_eval(line)
            sections = str(sentences).split("[")
            for section in sections:
                if "'{}'".format(word) in section:
                    fishing_count += 1
    return fishing_count

def count_word_num_json(json_path, word):
    count = 0
    with open(json_path, 'r') as file:
        data = json.load(file)
        for image_path, detections in data.items():
            for detection in detections:
                detection_type = detection['type']
                if detection_type == word:
                    count += 1
    return count

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="Count the occurrences of a word in a text or JSON file.")
    # "../result/fish/ori_data.txt"    "../result/fish/fish_result.json"
    parser.add_argument("--file", type=str, default="../result/fish/ori_data.txt", help="Path to the input file (txt or json).")
    parser.add_argument("--word", type=str,default="fishing", help="Target word to count.")
    parser.add_argument("--format", type=str, choices=["txt", "json"], default="txt", help="File format (txt or json).")

    args = parser.parse_args()

    if args.format == "txt":
        count_function = count_word_num_txt
    elif args.format == "json":
        count_function = count_word_num_json
    else:
        print("Invalid file format. Please choose 'txt' or 'json'.")
        exit(1)

    if args.format == "txt":
        counts = count_function(args.file, args.word)
    elif args.format == "json":
        counts = count_function(args.file, args.word)

    print("{}文件: 出现 '{}' 的次数:".format(args.file, args.word), counts)

逻辑

  1. 导入了argparse、ast和json模块,用于处理命令行参数、将字符串转换为Python对象以及处理JSON文件。
  2. 定义了两个函数,count_word_num_txt和count_word_num_json,用于分别统计文本文件和JSON文件中某个目标单词的出现次数。
  3. 在count_word_num_txt函数中,它接受文本文件路径(txt_path)和目标单词(word)作为参数,然后初始化一个计数器fishing_count为0。它打开文本文件,逐行读取文件内容,将每一行使用ast.literal_eval转换为Python对象,然后将对象转换为字符串,并通过split(“[”)来分割成多个部分。接着,它遍历每个部分,检查目标单词是否出现在部分中(在单引号内),如果是,就将计数器增加1,最后返回计数器的值。
  4. 在count_word_num_json函数中,它接受JSON文件路径(json_path)和目标单词(word)作为参数,然后初始化一个计数器count为0。它打开JSON文件,使用json.load将JSON数据加载为Python对象,然后遍历数据,逐个检查每个图片的检测内容中是否包含目标单词,如果包含,就将计数器增加1,最后返回计数器的值。
  5. 在if name == ‘main’:块中,它使用argparse来解析命令行参数,包括输入文件路径(–file)、目标单词(–word)和文件格式(–format)。默认的文件路径是"…/result/fish/ori_data.txt",默认的目标单词是"fishing",默认的文件格式是"txt"。
  6. 根据文件格式的选择,确定要使用的统计函数(count_function)是count_word_num_txt还是count_word_num_json。
  7. 最后,根据所选择的文件格式和指定的文件路径和目标单词,调用相应的统计函数来统计目标单词的出现次数,并打印出结果。

这个代码允许用户通过命令行参数来指定要统计的文件、目标单词以及文件格式,然后执行相应的统计操作,并打印出结果。

结果

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ZZY_dl

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值