In: Computer Science
How to count the number of words that only show up once in a text file, and replace those words with a character '(unique)' using Python? Without list is better.
In the below program , it will count the number of occurences of all the words.Then it will replace the single occurance word to (unique).This will be easier so that you can have the number of occurences of all the words.
The program is as follows:
text = open ("sample.txt" , "r") //Opens a file in read mode
d = dict() //just creating an empty Dictionary
for line in text : //Loop to go through each line of the file
line= line. strip() //Removes the spaces for counting
line=line. lower() //converts to lower case for easy identification
words = line. split() //Split the lines into words
for word in words : //Iterate over each word in a line
if word in d : //Check if the word is in the directory
d[word]=d[word]+1 //Increment the number of times
else :
d[word]= 1
print(d)
if d[word] ==1 : //If the word is present only once
print("unique") //Prints unique
Note: Read the linewise comments for better understanding.