1

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)
petezurich
  • 9,280
  • 9
  • 43
  • 57
Markus Pe
  • 21
  • 7
  • 1
    Why do you not want to use dictionaries or lists? Those are essential tools that you will need to use for most of your python programming experience. That said - this question has been asked in many forms on SO - https://stackoverflow.com/questions/37772253/how-to-count-all-occurrences-of-a-word-in-a-string-using-python | https://stackoverflow.com/questions/8742732/python-number-of-word-occurrences – Duniyadnd Jan 03 '23 at 11:47
  • I haven't learnt about dictionaries yet – Markus Pe Jan 03 '23 at 11:50

1 Answers1

2

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])
Nick
  • 101
  • 3
  • Thank you for your help. Just a question: in my case I don't know what word I will look for. I just need to find any duplicates, fi there are. This text file will be updated frequently so it might be that a word has not duplicate anymore. Thank you – Markus Pe Jan 03 '23 at 12:04