I am pretty new in Python and I am not sure if I did everything right in my program. May someone to check it, please. Thank you!
- First of all, I have a text file, for example,
abc.txt
. - I have to create a dictionary and for this, I have to split the sentences into a list of words and convert each word to lowercase.
- Then I have to assign a counter to each word in my dictionary and increment it every time when I meet this word in sentence one more time.
- Finally, I have to divide the word count by sum of all counts
(prob = count(word) / sum(count of all words in dict)
and write this probability into new file calledx.txt
.
Here is what I got so far:
import sys
filename = 'abc.txt'
new_dict ={}
total_count = 0
with open(filename, "r") as fp:
for line in fp:
words = line.split()
for word in words:
word = word.lower()
if not word in new_dict:
new_dict[word] = 1
else:
new_dict[word] +=1
total_count +=1
probab = new_dict[word]/ total_count
print(probab)
fp.close()
output_file = 'x.txt'
with open(output_file, "w") as fs:
fs.write(str(probab))
fs.close()
and my output is 0.0006865437426441742
and my input is 0.0006865437426441742
Are you sure this is your input? \$\endgroup\$"i am going"
will give you['i,','am','going']
and" i am going."
will give you['i', 'am','going.']
. \$\endgroup\$