count how many times the same word occurs in a txt file

Question:

Hello I am struggling with this:
I have a txt file that once open looks like this:

Jim, task1n
Marc, task3n
Tom, task4n
Jim, task2n
Jim, task6n

And I want to check how many duplicate names there are. I am interested only in the first field (i.e person name).

I tried to look for an answer on this website, but I could not find anything that helped, as in my case I don’t know which name is duplicate, since this file txt will be updated frequently.

As I am new to Python/programming is there a simple way to solve this without using any dictionaries or list comprehensions or without importing modules?

Thank you

same_word_count = 0
with open('tasks.txt','r') as file2:
content = file2.readlines()
for line in content:
    
    split_data = line.split(', ')
    user = split_data[0]
    word = user

    if word == user:
            same_word_count -= 1
print(same_word_count)
Asked By: Markus Pe

||

Answers:

You can do the following.

word = "Word" # word you want to count
count = 0
with open("temp.txt", 'r') as f:
    for line in f:
        words = line.split()
        for i in words:
            if(i==word):
                count=count+1
print("Occurrences of the word", word, ":", count)

Or you can get list of all words occurrences

# Open the file in read mode
text = open("sample.txt", "r")
  
# Create an empty dictionary
d = dict()
  
# Loop through each line of the file
for line in text:
    # Remove the leading spaces and newline character
    line = line.strip()
  
    # Convert the characters in line to
    # lowercase to avoid case mismatch
    line = line.lower()
  
    # Split the line into words
    words = line.split(" ")
                         
  
    # Iterate over each word in line
    for word in words:
        # Check if the word is already in dictionary
        if word in d:
            # Increment count of word by 1
            d[word] = d[word] + 1
        else:
            # Add the word to dictionary with count 1
            d[word] = 1
  
# Print the contents of dictionary
for key in list(d.keys()):
    print(key, ":", d[key])
Answered By: Nick
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.