Gabriel Ferguson
Gabriel Ferguson

Reputation: 19

count occurrences of word in json file python

I am working on a program that needs to be able to count the amount of time a word (like parsed_text) is mentioned in a JSONa file. So far I have come up with some code that I think could work but it never gets the amount a word is used correctly. This is my Code:

with open("Adlogica logo picker-ATrecords.json", encoding="utf8") as f:
    ATdata = json.load(f)
    total = sum(1 for line in f.readlines() if 'parsed_text' in line)
    print(total)

Any help is greatly appreciated

Upvotes: 0

Views: 1958

Answers (2)

zr0gravity7
zr0gravity7

Reputation: 3194

Use re.findall() from the re (RegEx) module to find all occurrences of the search word (where it is surrounded by word boundaries).

import re

with open("Adlogica logo picker-ATrecords.json", encoding="utf8") as f:
    # ATdata = json.load(f) # not necessary

    searchWord = 'parsed_text'

    total = 0
    for line in f:
        total += len(re.findall(f"\b{searchWord}\b", line))

    print(total)

Upvotes: 0

May.D
May.D

Reputation: 1910

A solution that I found more elegant than looping.

search_word = 'parsed_text'
with open("some_file.json", "r") as f:
    data = f.read()
    total = data.count(search_word)

Upvotes: 1

Related Questions