-3

I'm trying to use dictionary and some loops to figure out how many times a word was written and if user types in "quit" then the program should stop. This is what I have so far:

import string 

text = open('text.txt', 'r') 

val = dict()

for i in text:
    i = i.strip().lower().split(" ")
    print(i)

This is the output necessary

ObjectJosh
  • 601
  • 3
  • 14
jagac
  • 5
  • 1
  • Please repeat [on topic](https://stackoverflow.com/help/on-topic) and [how to ask](https://stackoverflow.com/help/how-to-ask) from the [intro tour](https://stackoverflow.com/tour). “Show me how to solve this coding problem” is not a Stack Overflow issue. We expect you to make an honest attempt, and *then* ask a *specific* question about your algorithm or technique. Stack Overflow is not intended to replace existing documentation and tutorials. – Prune Mar 30 '21 at 22:16
  • Off-site links and images of text are not acceptable; we need your question to be self-contained, in keeping with the purpose of this site. – Prune Mar 30 '21 at 22:17
  • Perhaps something like [Counting the frequencies in a list using dictionary in Python](https://www.geeksforgeeks.org/counting-the-frequencies-in-a-list-using-dictionary-in-python/) or [Item frequency count in Python](https://stackoverflow.com/q/893417/15497888) might be a good place to start in solving your problem. – Henry Ecker Mar 30 '21 at 22:20
  • When you get to the point of a specific question, please supply the expected [minimal, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) (MRE). We should be able to copy and paste a contiguous block of your code, execute that file, and reproduce your problem along with tracing output for the problem points. This lets us test our suggestions against your test data and desired output. Your posted code fails on a non-existent file. Don't expect us to enter test data, or to build a test file. Instead, simply hard-code a test case that causes the problem. – Prune Mar 30 '21 at 22:25

1 Answers1

0

This is one approach to the problem:

with open('text.txt', 'r') as file:
    data = file.read()

data = data.replace('\n', ' ')
data = data.split(' ')
while True:
    counter = 0
    search_term = input('Word: ')
    if search_term == 'quit':
        break
    for word in data:
        if word.lower() == search_term.lower() or word.lower() == search_term.lower() + '.':
            counter += 1
    if counter == 0:
        print('None found!')
    else:
        print(f'Number of "{search_term}": {counter}')

Matiiss
  • 5,970
  • 2
  • 12
  • 29