So I am writing a program that will take in user input and then will take the user input and compare it to a set list and then tell me how many words from the user input are in the given list.
For Example:
list = ['I','like','apples'] # set list
user_in = input('Say a phrase:')
# the user types: I eat apples.
#
# then the code will count and total the similar words
# in the list from the user input.
I've gotten close with this, I know I might have to convert the user input into a list itself. just need help comparing and counting matching words.
Thank you.
len([word for word in user_in if word in list])
Try like this :
similarWords=0 #initialize a counter
for word in user_in.split():
if word in list: #check and compare if word is in set list
similarWords+=1 #increase counter by 1 every time a word matches
Well, you can split your user input with user_in.split(' ').
Then compare each word in the user_in_list with a word in the check list and increase the counter when this is the case:
list = ['I','like','apples'] # set list
user_in = input('Say a phrase:')
ui = user_in.split(' ')
count = 0
for word in ui:
if word in list:
count += 1
print(count)
Try this,
l1 = ['I','like','apples'] # set list
user = input('Say a phrase:')
a=user.split(' ')
k=0
print(a)
for i in l1:
if i in l1:
k+=1
print("similar words:",k)
Hope this helps you!
By using the function split() you can split the given phrase into words.
And it is better to use a ui.lower() or ui.upper() to avoid case sensitivity
li = ['i', 'like', 'apples'] #initial list
ui = input('say a phrase') #taking input from user
ui = ui.lower() #converting string into lowercase
ui_list = ui.split() #converting phrase into list containing words
count = 0
for word in ui_list:
if word in li:
print(word)
count += 1
print(count) #printing matched words
Related
Condition:
The search words need to be stored in the list;
Search regardless of the case of the letters of the word;
A word can be separated from other words by a space, punctuation marks;
If the word is in the text, but in an inverted form, it should be taken into account in the search statistics.
You cannot use split.
My current code:
The problem is that it only accepts one word, not a sentence. I tried to translate searchW into a list, but this leads to errors (TypeError: list indexes must be integers or slices, not str).
def task1(text,searchW):
for i in text:
if i.isalpha():
letters.append(i)
res = "".join(letters).lower() #combine characters
count = res.count(searchW.lower()) +res.count(searchW[::-1].lower()) # finding words and
inverted versions and counting their number
if len(res) != len(searchW):
count+=0
print(f"words found in normal and inverted form - {count} times(a).")
text = input("enter text:")
searchW = input("enter search words:")
letters = [ ] #a list that consists of letters contained in the text
task1(text=text,searchW= searchW)
Use a loop to get a list of words
text = input("enter text:")
searchW = []
print("enter search words:")
while True:
s = input("> ").strip()
if not s:
break
searchW.append(s)
task1(text, searchW)
Then sum the counts over each word
count = 0
for w in searchW:
w = w.lower()
count += res.count(w)
count += res.count(w[::-1])
You shouldn't compare the length of res string to the length of the search list
A word can be separated from other words by a space, punctuation marks
If your have text car.at, then rat search word will be counted by your code... Unclear if that's expected. If not, you need to rethink your res variable
This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 2 years ago.
I have a list of words, and a function that searches for a word by its length and the letters inside the word.
The for loop at the end cycles through the list of possible words (generated by the given length), and it should either print the word if it contains the given letter, or delete the word from the list of possible words if it does not contain the given letter.
How can I achieve this here:
wlist = ['Apple', 'Banana', 'Cherry', 'Donkey']
def wordSearch(wlist):
posWords = []
length = int(input('Enter length of word: '))
print("POSSIBLE WORD(S):")
for word in wlist:
stripWord = word.replace(' ', '')
if len(stripWord) == length:
print("%s (%s)" % (word, length))
posWords.append(word)
while True:
searchOptions = ['Add Known Letter', 'Exit']
searchIndex, item = chooseFromMenu(searchOptions)
if searchIndex == 0:
letter = input('Enter letter: ')
print("POSSIBLE WORD(S):")
for word in posWords:
if letter in word:
print(word)
else:
# remove word from list somehow
else:
break
Specifically this block:
letter = input('Enter letter: ')
print("POSSIBLE WORD(S):")
for word in posWords:
if letter in word:
print(word)
else:
# remove word from list somehow
I've tried to do del word and posWords.pop(word) but neither seem to work.
I also tried .remove() but I cant exactly remember what I did with that.
I'll go into more detail with the problem I'm having here...
If I type in the letter 'e', it should remove 'Banana' from the list of possible words so that when I type 'n' I should only get 'Donkey', not 'Donkey' and 'Banana'.
If that makes sense.
I have just tried posWords.remove(word) and it hasn't done this either...
You can iterate over the list in reverse, so that removing an element doesn't affect the rest of the iteration.
for i in range(len(posWords)-1, -1, -1):
if letter in posWords[i]:
print(posWords[i])
else:
posWords.pop(i)
This is the solution in this answer to the question you said didn't solve your problem.
Note that the argument to pop() is the list index, not a list element.
You can use a while loop and only increase the iterator, if no item is removed.
i = 0
while i < len(posWords):
if letter in word:
print(word)
i += 1
else:
del posWords[i] # posWords.pop(i) does the same
This works, because if an item is removed, the next items index is reduced by 1 so i now points to the next item
If I'm understanding your question properly then the following should work:
letter = input('Enter letter: ')
print("POSSIBLE WORD(S):")
for word in posWords[:]:
if letter in word:
print(word)
else:
posWords.remove(word)
I have a list containing words that starts with "INF.." and "INFO.."
When user inputs in "INF", I don't want the words that start with INFO printed too. How can i make a limit so that the "info" words are not printed?
weirdList = {"INF432", "INF678", "INFO123", "INFO654"}
filtered_list = []
for word in weirdList
if word[0:3] == input:
filtered_list.append(word)
My wish is that only "INF432" and "INF678" gets printed, and not "INFO.." when the user asks for words starting with "INF"
From you examples, I could see that you want to keep only the items that start with "INF" and are followed by numbers.For example "INFO" is "INF" followed by a "O".
This can be achieved by this:
weirdList = {"INF432", "INF678", "INFO123", "INFO654"}
filtered_list = []
word1=input("enter something: ")
for word in weirdList:
if word.startswith(word1) and word.replace(word1,"")[0].isnumeric():
filtered_list.append(word)
print(filtered_list)
Output:
enter something: INF
['INF432', 'INF678']
This approach eliminates also "INFS01" and so on and works for other criteria than "INF".
First, weirdList is a set not a list. The reason your code doesn't work is because the condition is True for all your elements:
'INF432'[0:3] will output 'INF'
'INFO123'[0:3] will also output 'INF'
What you can do is filter out the items that start with INFO:
weirdList = {"INF432", "INF678", "INFO123", "INFO654"}
filtered_list = []
for word in weirdList:
if not word.startswith('INFO'):
filtered_list.append(word)
This can also be achieved with a list comprehension:
weirdList = ["INF432", "INF678", "INFO123", "INFO654"]
filtered_list = [word for word in weirdList if not word.startswith('INFO')]
Note that in my last example I've changed the weirdList to an actual list.
If you want to add items to a list based on user input, and ignore the INFO items, you could do it like this:
user_item_list = []
user_input = input('Enter item here: ')
if not user_input.startswith('INFO'):
user_item_list.append(user_input)
print(user_item_list)
I am working on a small problem for fun, sent to me by a friend. The problem requires me to populate an array with common words from a text file, and then print all the words from this list containing certain characters provided by the user. I am able to populate my array no problem, but it seems the part of the code that actually compares the two lists is not working. Below is the function I've written to compare the 2 lists.
#Function that prompts user for the set of letters to match and then compares that list of letters to each word in our wordList.
def getLetters():
#Prompt user for list of letters and convert that string into a list of characters
string = input("Enter your target letters: ")
letterList = list(string)
#For each word in the wordList, loop through each character in the word and check to see if the character is in our letter list, if it is increase matchCount by 1.
for word in wordList:
matchCount = 0
for char in word:
if char in letterList:
matchCount+=1
#If matchCount is equal to the length of the word, all of the characters in the word are present in our letter list and the word should be added to our matchList.
if matchCount == len(word):
matchList.append(word)
print(matchList)
The code runs just fine, I don't get any error output, but once the user enters their list of letters, nothing happens. To test I've tried a few inputs matching up with words I know are in my wordList (e.g. added, axe, tree, etc). But nothing ever prints after I enter my letter string.
This is how I populate my wordList:
def readWords(filename):
try:
with open(filename) as file:
#Load entire file as string, split string into word list using whitespace as delimiter
s = file.read()
wordList = s.split(" ")
getLetters()
#Error handling for invalid filename. Just prompts the user for filename again. Should change to use ospath.exists. But does the job for now
except FileNotFoundError:
print("File does not exist, check directory and try again. Dictionary file must be in program directory because I am bad and am not using ospath.")
getFile()
Edit: Changed the function to reset matchCount to 0 before it starts looping characters, still no output.
Your code only needs a simple change:
Pass wordList as a parameter for getLetters. Also if you like you could make a change in order to know if all the letters of the word are in the letter list.
def getLetters(wordList):
string = input("Enter your target letters: ")
letterList = list(string)
matchList = []
for word in wordList:
if all([letter in letterList for letter in word]):
matchList.append(word)
return matchList
And in readWords:
def readWords(filename):
try:
with open(filename) as file:
s = file.read()
wordList = s.split(" ")
result = getLetters(wordList)
except FileNotFoundError:
print("...")
else:
# No exceptions.
return result
Edit: add a global declaration to modify your list from inside a function:
wordList = [] #['axe', 'tree', 'etc']
def readWords(filename):
try:
with open(filename) as file:
s = file.read()
global wordList # must add to modify global list
wordList = s.split(" ")
except:
pass
Here is a working example:
wordList = ['axe', 'tree', 'etc']
# Function that prompts user for the set of letters to match and then compares that list of letters to each word in our wordList.
def getLetters():
# Prompt user for list of letters and convert that string into a list of characters
string = input("Enter your target letters: ")
letterList = list(string)
# For each word in the wordList, loop through each character in the word and check to see if the character is in our letter list, if it is increase matchCount by 1.
matchList = []
for word in wordList:
matchCount = 0
for char in word:
if char in letterList:
matchCount += 1
# If matchCount is equal to the length of the word, all of the characters in the word are present in our letter list and the word should be added to our matchList.
if matchCount == len(word):
matchList.append(word)
print(matchList)
getLetters()
output:
Enter your target letters: xae
['axe']
I am trying to create a program in python that takes a sentence from a user and jumbles the middle letters of said word, but keeping the other letters intact...Right now I have code that will rearrange all the user input's and just forgets about the spaces...I'll let my code speak for myself.. IT works fine for a single word input, I guess I will just summarize it...
I need to randomize each word the user enters keeping the other words intact afterwards..
import random
words = input("Enter a word or sentence") #Gets user input
words.split()
for i in list(words.split()): #Runs the code for how many words there are
first_letter = words[0] #Takes the first letter out and defines it
last_letter = words[-1] #Takes the last letter out and defines it
letters = list(words[1:-1]) #Takes the rest and puts them into a list
random.shuffle(letters) #shuffles the list above
middle_letters = "".join(letters) #Joins the shuffled list
final_word_uncombined = (first_letter, middle_letters, last_letter) #Puts final word all back in place as a list
final_word = "".join(final_word_uncombined) #Puts the list back together again
print(final_word) #Prints out the final word all back together again
Your code is almost right. Corrected version would be like this:
import random
words = raw_input("Enter a word or sentence: ")
jumbled = []
for word in words.split(): #Runs the code for how many words there are
if len(word) > 2: # Only need to change long words
first_letter = word[0] #Takes the first letter out and defines it
last_letter = word[-1] #Takes the last letter out and defines it
letters = list(word[1:-1]) #Takes the rest and puts them into a list
random.shuffle(letters) #shuffles the list above
middle_letters = "".join(letters) #Joins the shuffled list
word = ''.join([first_letter, middle_letters, last_letter])
jumbled.append(word)
jumbled_string = ' '.join(jumbled)
print jumbled_string
So I read this question, during lunch at the apartment, then I had to wade through traffic. Anyways here is my one line contribution. Seriously alexeys' answer is where it's at.
sentence = input("Enter a word or sentence")
print " ".join([word[0] + ''.join(random.sample(list(word[1:-1]), len(list(word[1:-1])))) + word[-1] for word in sentence.split()])
If i understand your question correctly it looks like you are on track, you just have to extend this for every word
randomized_words = []
for word in words.split():
#perform your word jumbling
radomized_words.append(jumbled_word)
print ' '.join(randomized_words)
This creates a separate jumbled word list. Each word in the users word input is jumbled and added to the list to retain order. At the end, the jumbled words list is printed. Each word is in the same order as entered by the user but the letters are jumbled.