I tried looking for an answer to this problem but it didn't work. (btw I am 15 and basically just started python)
This is my program:
all = []
count = {}
line = input("Enter line: ")
while line:
word = line.split()
line = input("Enter line: ")
for w in word:
if w in count:
count[w] += 1
else:
count[w] = 1
for word in sorted(count):
print(word, count[word])
This is the answer I'm getting:
Enter line: which witch
Enter line: is which
Enter line:
is 1
which 1
When I should be getting:
Enter line: which witch
Enter line: is which
Enter line:
is 1
which 2
witch 1
Please, can someone help?
for w in word: loop is executed outside while line: loop. It means that first you produce single word list for each line and then you skip each such list end executes for w in word: only for last word list.
To fix it change indentation of whoole for w in word: loop (this line and 4 lines below). Move it 4 spaces to the right.
all = []
count = {}
line = input("Enter line: ")
while line:
print("line is :" + line )
word = line.split()
line = input("Enter line: ")
for w in word:
if w in count:
count[w] += 1
else:
count[w] = 1
for word in sorted(count):
print(word, count[word])
It's because indentation in python is used to determine grouping of statements.
Here is way using Counter from collections module, it will give a dict with list elements as key at its frequency as values, it may help you to reduce the code length and use of for loop, You can get more idea about Counter from here
:
from collections import Counter
all = []
line = input("Enter line: ")
while line:
all.extend(line.split())
line = input("Enter line : ")
for i,j in Counter(all).items():
print(i, j)
Related
So this is a code of me trying to find a word a user inputs and look up how many lines contain the word and if no lines contain the word output not found however when i input a word that I know exist in the file it returns 0 and not only is the word in the file it doesn't even output not found like I want it to. (here is my code)
response = input('Please enter words: ')
letters = response.split()
count = 0
with open("alice.txt", "r", encoding="utf-8") as program:
for line in program:
if letters in line:
count += 1
if(count < 1):
print("not found")
print(count)
What you're doing isn't gonna work the split function returns a list of strings and you're checking that list against a single string.
Is this what you wanted to do?
response = input("Please enter a word: ")
count = 0
with open("alice.txt", 'r') as program:
for line in program:
if response in line:
count += 1
if count == 0:
print("not found")
print(count)
You dont need the split function and the place of if condition is wrong in your code. Please refer below code.
response = input('Please enter word: ')
count = 0
with open("alice.txt", "r", encoding="utf-8") as program:
for line in program:
if response in line:
count += 1
if count == 0:
print('Not found')
else:
print(count)
You had an issue with opening the txt file as a single line, and not as a list of the individual lines.
Adding ".readlines()" can fix this issue!
I also went ahead and set the individual lines as 'line', where I then search for the input word in the new 'line' variable.
response = input('Please enter words: ')
letters = response.split()
count = 0
foo = open(
"alice.txt", "r",
encoding="utf-8").readlines()
for line in foo:
for word in letters:
if word in line:
count += 1
if(count < 1):
print("not found")
else:
print(count)
Complete beginner, searched a lot of threads but couldn't find a solution that fits me.
I have a text file, python_examples.txt which contains some words. On line four, the word hello appears twice in a row, like "hello hello".
My code is supposed to find the word the user inputs and count how many times it appears, it works but as I said, not if the same word appears multiple times on the same row. So there are 2 hellos on line 4 and one on line 13 but it only finds a total of 2 hellos. Fixes? Thanks,
user_input = input("Type in the word you are searching for: ")
word_count = 0
line_count = 0
with open ("python_example.txt", "r+") as f:
for line in f:
line_count += 1
if user_input in line:
word_count += 1
print("found " + user_input + " on line " + str(line_count))
else:
print ("nothing on line " + str(line_count))
print ("\nfound a total of " + str(word_count) + " words containing " + "'" + user_input + "'")
you can use str.count:
word_count += line.count(user_input)
instead of :
word_count += 1
it will count all appearance of user_input in the file line
The issue is with these two lines:
if user_input in line:
word_count += 1
You increase the count by 1 if the input appears on the line, regardless of whether it appears more than once.
This should do the job:
user_input = input("Type in the word you are searching for: ")
word_count = 0
with open("python_example.txt") as f:
for line_num, line in enumerate(f, start=1):
line_inp_count = line.count(user_input)
if line_inp_count:
word_count += line_inp_count
print(f"input {user_input} appears {line_inp_count} time(s) on line {line_num}")
else:
print(f"nothing on line {line_num}")
print(f"the input appeared a total of {word_count} times in {line_num} lines.")
Let me know if you have any questions :)
One option is use a library to parse the words in your text file rather than iterating one line at a time. There are several classes in nltk.tokenize which are easy to use.
import nltk.tokenize.regexp
def count_word_in_file(filepath, word):
"""Give the number for times word appears in text at filepath."""
tokenizer = nltk.tokenize.regexp.WordPunctTokenizer()
with open(filepath) as f:
tokens = tokenizer.tokenize(f.read())
return tokens.count(word)
This handles awkward cases like the substring 'hell' appearing in 'hello' as mentioned in a comment, and is also a route towards case-insenstive matching, stemming, and other refinements.
i'm doing a python course and one of the questions asks me to write a program that counts words like this:
Enter line: which witch
Enter line: is which
Enter line:
is 1
which 2
witch 1
The code i have so far is:
occurences = {}
line = input('Enter line: ')
while line:
m = line.split()
for i in m:
if i in occurences:
occurences[i] += 1
else:
occurences[i] = 1
line = input('Enter line: ')
for word in sorted(occurences):
print(word, occurences[word])
But when I run this code, it either tells me every word occured only once or some other strange output. Thanks for the help!
Here is an example of it not working:
Enter line: test test test
Enter line: one two test
Enter line: one
Enter line:
test 3
This is the output i get while the expected output is:
test 4
two 1
one 2
Your input inside for loop is causing the problem, please try this:
occurences = {}
line = input('Enter line: ')
while line:
m = line.split()
print( m)
for i in m:
if i in occurences:
occurences[i] += 1
else:
occurences[i] = 1
print(occurences)
line = input('Enter line: ')
for word in sorted(occurences):
print(word, occurences[word])
By resetting the input inside the for loop, you are asking for new input after the first word is counted, and ignoring the subsequent words in the string.
When i ran the code i got no output at all, this is because you have a infinite loop by asking the user for another line at the end of the "While" loop, which cause it to do indefinitely.
To match what you were doing before I've changed your code a tiny bit
occurences = {}
line = input('Enter line: ')
while line:
m = line.split()
for i in m:
if i in occurences:
occurences[i] += 1
else:
occurences[i] = 1
break ## Once the word has been put into occurences it breaks
## so that the next loop can run
for word in sorted(occurences):
print(word, occurences[word])
if you want it to go forever until the user quits the program then you would do this:
while True:
occurences = {}
line = input('Enter line: ')
while line:
m = line.split()
for i in m:
if i in occurences:
occurences[i] += 1
else:
occurences[i] = 1
break
for word in sorted(occurences):
print(word, occurences[word])
This simple while loop that stops at a sentinel value and otherwise continuously asks for user input. How would I use the incrementing line count variable to display after on what line the user inputted certain things? I would guess use of a dictionary is needed?
lineCount = 1
d = {} #is this needed?
q = raw_input("enter something")
while q != "no":
lineCount += 1
q = raw_input("enter something")
#code here that stores each new input with its respective line and prints what the user inputted on each corresponding line when the loop ends
Many thanks in advance
Using array:
lines = []
def add_line(line):
lines.append(line)
def print_lines():
for i in range(len(lines)):
print "%d: %s" % (i, lines[i])
lineCount = 1
q = raw_input("enter something")
add_line(q)
while q != "no":
lineCount += 1
q = raw_input("enter something")
if q != "no":
add_line(q)
print_lines()
Exactly like you said, using a dictionary:
d = {}
lineCount = 1
q = raw_input("enter something: ")
while q != "no":
lineCount += 1
q = raw_input("enter something: ")
d[lineCount] = q
Then you could just query your dictionary if you want to know what the user input at a desired line as d[desired_line].
Assuming you have a simple dictionary, such as:
d = {2: 'b', 3: 'c', 4: 'd', 5: 'no', 6: 'c'}
Then if you'd like to print out the lines where a desired word appear you could define a function like so:
def print_lines(my_dict, word):
lines = [line for line, ww in my_dict.iteritems() if ww == word]
return lines
You could call this function with your dictionary (d) and the word your looking for, let's say 'c':
print_lines(d, 'c')
Finally, could iterate over the set of words (unique_words using set) you have and print the lines they appear on by calling the previous function:
def print_words(my_dict):
unique_words = set([word for word in my_dict.itervalues() if word != 'no'])
for word in sorted(unique_words):
print("'{0}' occurs in lines {1}".format(word, print_lines(my_dict, word)))
UPDATE (for sentences instead of single words):
In case you want to work with sentences, rather than single words per line, you'll need to modify your code as follows:
First, you could define a function to handle the user input and build the dictionary:
def build_dict():
d = {}
lineCount = 1
q = raw_input("enter something: ")
while q != "no":
d[lineCount] = q
lineCount += 1
q = raw_input("enter something: ")
return d
Let's say you build a dictionary like such:
d = {1: 'a x', 2: 'a y', 3: 'b x'}
Then you can define a helper function that tells you at which line a particular word occurs:
def occurs_at(my_dict, word):
lines = [line for line, words in my_dict.iteritems() if word in words]
return lines
Finally, you can query this function to see where all your words occur at (and you can decide which words to ignore, e.g. 'a').
def print_words(my_dict, ignored=['a']):
sentences = [sentences.split(' ') for sentences in my_dict.itervalues()]
unique_words = set([word for sentence in sentences for word in sentence])
for word in sorted(unique_words):
if word not in ignored:
print("'{0}' occurs in lines {1}".format(word, occurs_at(my_dict, word)))
This is what I have so far:
while len(words) != 5:
words = raw_input("Enter a 5 worded sentence: ").split()
print "Try again. The word count is:", wordCount
if len(words) == 5:
print "Good! The word count is 5!"
The problem is I get this:
Enter a 5 worded sentence: d d d d
Try again. The word count is: 4
Enter a 5 worded sentence: d d d d d d
Try again. The word count is: 4
Enter a 5 worded sentence: d d d d d
Try again. The word count is: 4
Good! The word count is 5!
When I enter more or less than 5 words, it keeps that word count and doesn't change.
Since Python doesn't have a do-while loop like some other languages, this idiom prevents duplication of the raw_input function, and makes sure the loop runs at least once. Make sure to update word_count after getting new input.
while 1:
words = raw_input("Enter a 5 worded sentence: ").split()
word_count = len(words)
if word_count == 5: break
print "Try again. The word count is:", word_count
print "Good! The word count is 5!"
You just need to re-order some of your logic:
# prompt before entering loop
words = raw_input("Enter a 5 worded sentence: ").split()
while len(words) != 5:
print "Try again. The word count is:", len(words)
words = raw_input("Enter a 5 worded sentence: ").split()
# no need to test len again
print "Good! The word count is 5!"
The variable wordCount should be updated inside the loop, after you accept the input. Only then it will reflect the new value. Something like this:-
while len(words) != 5:
words = raw_input("Enter a 5 worded sentence: ").split()
wordCount = len(words)
print "Try again. The word count is:", wordCount
if len(words) == 5:
print "Good! The word count is 5!"
I think your code snippet is missing parts. Anyways, you should evaluate the wordCount after raw_input so that it gets updated with new values.
wordCount = 0
while wordCount != 5:
words = raw_input("Enter a 5 worded sentence: ").split()
wordCount = len(words)
print "Try again. The word count is:", wordCount
print "Good! The word count is 5!"
def xlen(string_data):
try:
count = 0
while 1:
string_data[count]
count = count + 1
except(IndexError):
print count
xlen('hello')