Accessing certain words in an split list - python

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.

Related

How to add the ability to search for a set of words in the application?

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

Using itertools in python to create a wordlist, How can I make it work on a list of words instead of the current hardcoded word_list[0]?

char = input("Enter Char's to Combine with the Keyword: ")
n = int(input("Number of Char's Added to Keyword (2-9) :"))
letters = itertools.product(char,repeat=int(n))
for i in letters:
wrdLst.append(word_list[0] + "".join(i) + '\n')
save(wrdLst)
I'm using Itertools to create a wordlist using a baseword set by the user, word_list[0] .It currently works but I'd like to be able to perform the same thing on the entire list of items and not just word_list[0]
Pretty obvious, isn't it?
for word in word_list:
for i in letters:
wrdLst.append( word + ''.join(i) )
You should add the newline when you write it, not in the list.
What's the point of this? Your list will get very large very quickly and isn't very useful. With an 8 letter word and n=8, you're already at 16 million variations per word.

How does this code only print out the initials of a string?

This is the function:
def initials(phrase):
words = phrase.split()
result = ""
for word in words:
result += word[0]
return result.upper()
This is an exercise on my online course. The objective is to return the first initials of a string capitalized. For example, initials ("Universal Serial Bus") should return "USB".
phrase is a str type object.
str objects can have functions applied to them through their methods. split is a function that returns a list containing multiple str objects. This is stored in words
the for word in words takes each element of words and puts it in the variable word for each iteration of the loop.
The += function adds the first letter of word to result by accessing the first character of the str by using the [0] index of word.
Then the upper function is applied to the result.
I hope this clears it up for you.
def initials(phrase):
words = phrase.split()
result = ""
for word in words:
result += word[0]
return result.upper()
This:
Splits the phrase at every space (" "), with phrase.split(). .split() returns a list which is assigned to words
Iterates through the list words and adds the first letter of each word (word[0]) to the result variable.
Returns result converted to uppercase (result.upper())
def initials(phrase):
words = phrase.split()
result = ""
for word in words:
result += word[0].upper()
return result
print(ShortName("Active Teens Taking Initiative To Understand Driving Experiences"))
Should be: ATTITUDE
def initials(phrase):
words =phrase.split()
result=""+""
for word in words:
result += word[0].upper()
return result
print(initials("Universal Serial Bus")) # Should be: USB
print(initials("local area network")) # Should be: LAN
print(initials("Operating system")) # Should be: OS
Here is output:
USB
LAN
OS
This:
Splits the phrase at every space (" "+" ") and concatenate next one first letter,with phrase.split() returns a list which is assigned to words Iterates through the list words and adds the first letter of each word (word[0]) to the result variable.
Returns result converted to uppercase (result.upper())
strong text
def initials(phrase):
words = phrase.split()
result = ""
for word in words:
result += word[0].uppper()
return result

Printing only words from a list that contain characters from another 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 need to make it so the sentence and numbers that are outputted are stored into a file

The code I have made:
asks the user for a sentence,
makes it lower case so it is not case sensitive
splits the sentence into separate words so each word can have a number assigned to it according to its position
How can I add a part to my code that saves the sentence inputted by
the user as a file, along with the numbers that get assigned to each
word?
Here is my code:
sentence = input("Please enter a sentence")
sentence = sentence.lower()
sentence = sentence.split()
positions = [sentence.index (x) +1 for x in sentence]
print(sentence)
print(positions)
Use raw_input if you want to treat everything as strings. You do not need to store the positions but, instead, get them from the wonderful enumerate function. Then write to the file like so
sentence = raw_input("Please enter a sentence: ")
sentence = sentence.lower()
sentence = sentence.split()
open('filename.txt','w').writelines(["%d-%s\n"%(i+1,x) for (i,x) in enumerate(sentence)])
sentence = input("Please enter a sentence")
sentence = sentence.lower()
sentence = sentence.split()
wordPositionDict = {}
( wordPositionDict.get(x,[]).append(i+1) for i,x in enumerate(sentence))
print wordPositionDict[word]
append all the index for each word to dict. after iterate all the words in sentence you will have one dict which key is the words and value is the list of index

Categories