Home > front end >  count how many times the same word occurs in a txt file
count how many times the same word occurs in a txt file

Time:01-04

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

Jim, task1\n
Marc, task3\n
Tom, task4\n
Jim, task2\n
Jim, task6\n

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)

CodePudding user response:

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])
  • Related