How do I separate words in python? - python

I have tried to make this work with a phrase, but I am having issues with getting it to the ie to go at the end of the words. For example HankTIE ouYIE would be the output of the input Thank You.
Here is what I have:
string=input("Please input a word: ")
def silly_encrypter(string):
strr = string.split()
for strr in string:
first_letter_at_the_end = strr[1:] + strr[0]
ie_at_the_end = first_letter_at_the_end + "IE"
print (ie_at_the_end)
silly_encrypter(string)

You can do this:
string=input("Please input a word: ")
def silly_encrypter(string):
splitspace = string.split() # first split the string into spaces.
for s in splitspace: # then looping over each element,
strlist = list(s) # turn the element into a list
strlist.append(strlist[0]) # first number to the last
del strlist[0] # delete the first number
strlist[0] = strlist[0].capitalize() # Capitalize the first letter
strlist.append('IE') # add IE
print(''.join(strlist), end=" ") # join the list
silly_encrypter(string)

Upon reading the accepted answer, I had to provide a cleaner solution:
def silly_encryptor(phrase, suffix="IE"):
new_phrase = []
for word in phrase.split():
new_phrase.append(word[1:]+word[:1]+suffix)
return " ".join(new_phrase)
phrase = input("Please enter your phrase: ")
print (silly_encryptor(phrase))

Related

Replacing words in loop in python

what's wrong with this code : I am trying to run this code in a loop and with every loop it take two arguments but it does not works, it's runs only two time then printing constantly unnecessary things.
Code:
words= "this is my computer and my computer is super computer"
wordlist = words.split(" ")
changed_wordlist=[]
while (True):
replace = input("replace this: ")
with_this = input("with this: ")
for word in wordlist:
if word == replace:
replacedword = word.replace(replace, with_this)
print(replacedword,end=" ")
changed_wordlist.append(replacedword)
elif word!= replace:
print(word,end=" ")
changed_wordlist.append(word)
wordlist = changed_wordlist
I created an example that would change the words from the list, and then print its content after the change, both if the word was found or not. Try this:
words = "this is my computer and my computer is super computer"
wordlist = words.split(" ")
while (True):
replace = input("replace this: ")
with_this = input("with this: ")
# Iterate over the list, looking for the word
# to replace
for i in range(len(wordlist)):
# If we find the word, we replace it
if wordlist[i] == replace:
wordlist[i] = with_this
print("The list is now: " + str(wordlist))

python str object does not support item assignment

I'm trying to set the scrambled word from the list back to the list I have created, which is from split. I tried reading some of the solutions here and I think it's because you can't change the string in the list?
I'm not really sure correct me if I'm wrong :( . the sentence[i] = temp_word is giving the error. thanks in advance :)
class WordScramble:
def __init__(self):
self.user_input = input("Please give me a sentence: ")
def scramble(self):
# print what was input
print("The user input was: ", self.user_input)
# first scramble is just one word
print(self.user_input[0] + self.user_input[2] + self.user_input[1] + self.user_input[3:])
# reverse two indices
# particularly good to use is to switch the first two
# and the last two
# this only makes sense if you have a world that is longer than 3
# now try to scramble one sentence
sentence = self.user_input.strip().split(" ")
for i, word in enumerate(sentence):
if len(word) > 3:
temp_word = list(word)
if ',' in temp_word:
temp = temp_word[1]
temp_word[1] = temp_word[-3]
temp_word[-3] = temp
else:
temp = temp_word[1]
temp_word[1] = temp_word[2]
temp_word[2] = temp
temp_word = ''.join(temp_word)
sentence[i] = temp_word
sentence = ''.join(sentence)
print(sentence)
#print(" ".join(sentence))
# do just words first, then you can move on to work on
# punctuation
word_scrambler = WordScramble()
word_scrambler.scramble()
Because inside the for loop you wrote:
sentence = ''.join(sentence)
Thus, at the second iteration, the 'sentence' variable is now a string and in python, strings don't support item assignment as they are immutable variables. I think you meant to get this out of the for loop to print the final sentence.

Output first letter of each word of user input

I have this code
#Ask for word
w = input("Type in a word to create acronym with spaces between the words:")
#Seperate the words to create acronym
s = w.split(" ")
letter = s[0]
#print answer
print(s.upper(letter))
And I know that I need a for loop to loop over the words to get the first letter of each word but I can't figure out how to do it I tried many different types but I kept getting errors.
Try this. It prints a concatenated version of the first letter of each word.
w = input("Type in a word to create acronym with spaces between the words:")
print(''.join([e[0] for e in w.split()]).upper())
Try this
w = input("Type a phrase with a space between the words:")
w_up_split = w.upper().split()
acronym = ""
for i in w_up_split:
acronym += (i[0])
print(acronym)
for word in w.split(" "):
first_letter = word[0]
print(first_letter.upper())
In the code that you gave you are taking the first word in a list of lists.
s = w.split(" ")
letter = s[0]
If someone input 'Hi how are you' this s would equal
s == ["Hi"]["how"]["are"]["you"]
And then letter would equal the first index of s which would be ["Hi"]
You want to go through each word and take each letter
acronym = []
for x in s:
acronym.append(x[0])
Would get what you want.

Create one list with strings using read text file in Python

I want to make a jumble game in python that uses words from a text file rather than from words written directly into the python file(in this case the code works perfectly). But when I want to import them, I get this list:
[['amazement', ' awe', ' bombshell', ' curiosity', ' incredulity', '\r\n'], ['godsend', ' marvel', ' portent', ' prodigy', ' revelation', '\r\n'], ['stupefaction', ' unforeseen', ' wonder', ' shock', ' rarity', '\r\n'], ['miracle', ' abruptness', ' astonishment\r\n']]
I want words to be sorted in one single list, for example:
["amazement", "awe", "bombshell"...]
This is my python code:
import random
#Welcome the player
print("""
Welcome to Word Jumble.
Unscramble the letters to make a word.
""")
filename = "words/amazement_words.txt"
lst = []
with open(filename) as afile:
for i in afile:
i=i.split(",")
lst.append(i)
print(lst)
word = random.choice(lst)
theWord = word
jumble = ""
while(len(word)>0):
position = random.randrange(len(word))
jumble+=word[position]
word=word[:position]+word[position+1:]
print("The jumble word is: {}".format(jumble))
#Getting player's guess
guess = input("Enter your guess: ")
#congratulate the player
if(guess==theWord):
print("Congratulations! You guessed it")
else:
print ("Sorry, wrong guess.")
input("Thanks for playing. Press the enter key to exit.")
I have a text file with words:
amazement, awe, bombshell, curiosity, incredulity,
godsend, marvel, portent, prodigy, revelation,
stupefaction, unforeseen, wonder, shock, rarity,
miracle, abruptness, astonishment
Thank you for help and any suggestions!
quasi one-liner does it:
with open("list_of_words.txt") as f:
the_list = sorted(word.strip(",") for line in f for word in line.split())
print(the_list)
use a double for in a gen-comprehension
splitting against spaces is the trick: it gets rid of the line-termination chars and multiple spaces. Then, just get rid of the commas using strip().
Apply sorted on the resulting generator comprehension
result:
['abruptness', 'amazement', 'astonishment', 'awe', 'bombshell', 'curiosity', 'godsend', 'incredulity', 'marvel', 'miracle', 'portent', 'prodigy', 'rarity', 'revelation', 'shock', 'stupefaction', 'unforeseen', 'wonder']
Only drawback of this quick method is that if 2 words are only separated by a comma, it will issue the 2 words as-is.
In that latter case, just add a for in the gencomp like this to perform a split according to comma and drop the empty result string (if word):
with open("list_of_words.txt") as f:
the_list = sorted(word for line in f for word_commas in line.split() for word in word_commas.split(",") if word)
print(the_list)
or in that latter case, maybe using regex split is better (we need to discard empty strings as well). Split expression being blank(s) or comma.
import re
with open("list_of_words.txt") as f:
the_list = sorted(word for line in f for word in re.split(r"\s+|,",line) if word)
use
lst.extend(i)
instead of
lst.append(i)
split return a list and you append a list to list everytime. Using extend instead will solve your problem.
Please try the following code:
import random
#Welcome the player
print("""
Welcome to Word Jumble.
Unscramble the letters to make a word.
""")
name = " My name "
filename = "words/amazement_words.txt"
lst = []
file = open(filename, 'r')
data = file.readlines()
another_lst = []
for line in data:
lst.append(line.strip().split(','))
print(lst)
for line in lst:
for li in line:
another_lst.append(li.strip())
print()
print()
print(another_lst)
word = random.choice(lst)
theWord = word
jumble = ""
while(len(word)>0):
position = random.randrange(len(word))
jumble+=word[position]
word=word[:position]+word[position+1:]
print("The jumble word is: {}".format(jumble))
#Getting player's guess
guess = input("Enter your guess: ")
#congratulate the player
if(guess==theWord):
print("Congratulations! You guessed it")
else:
print ("Sorry, wrong guess.")
input("Thanks for playing. Press the enter key to exit.")
str.split() generates a list, so if you append it to your result you get a list of lists.
A solution would be to concatenate the 2 list (+)
You can get rid of the '\r\n' by stripping i before splitting it

Storing multiple inputs in one variable

I have a while loop, which will keep asking a user to input words until they type stop. The input is stored in a variable called sentence.
My question is how do I store multiple inputs into one variable.
My current code is
stop = "stop"
sentence = []
while sentence != stop:
sentence = input("Enter a word: ")
sentence = sentence
print(sentence)
I don't understand how I would keep storing variables from one input and print out all the variable stored separated by commas/spaces etc
All you need to do is append() your new variables to the array:
>>> a = []
>>> for x in range(5):
... a.append("Hello!")
...
>>> a
['Hello!', 'Hello!', 'Hello!', 'Hello!', 'Hello!']
At the end, if you need everything in a single variable you can use join():
>>> ",".join(a)
'Hello!,Hello!,Hello!,Hello!,Hello!'
stop = "stop"
# okay --- 'sentence' is a list. Good start.
sentence = []
while sentence != stop:
# ...but now you've replaced the list 'sentence' with the word that was just input
# NOTE that in Python versions < 3, you should use raw_input below.
sentence = input("Enter a word: ")
# ...and this does nothing.
sentence = sentence
print(sentence)
Works better if you do something like this:
stop = "stop"
sentence = []
# create a new variable that just contains the most recent word.
word = ''
while word != stop:
word = input("Enter a word: ")
# stick the new word onto the end of the list
sentence.append(word)
print(sentence)
# ...and convert the list of words into a single string, each word
# separated by a space.
print " ".join(sentence)
...or to re-design a bit to omit the 'stop', something like:
stop = "stop"
sentence = []
while True:
word = input("Enter a word: ")
if word == stop:
# exit the loop
break
sentence.append(word)
# ...and convert the list of words into a single string, each word
# separated by a space.
print " ".join(sentence)
Its pretty simple
stop = "stop"
sentence = []
all = ""
while sentence != stop:
sentence = input("Enter a word: ")
all += sentence + ","
print(all)
One of your problems is that you are constantly writing over your sentence variable.
What you want to do is make use of the list append method. Documentation on lists:
https://docs.python.org/3/tutorial/datastructures.html
Example:
a = []
a.append(1)
a.append(2)
a.append(3)
print(a)
[1, 2, 3]
Next, you are looking to end your code if the user enters "stop". So what you should do is check in your loop if "stop" was written, and make use of Python's break, to break out of the loop.
What this means is that you should change your loop to loop indefinitely until you get that stop, using while True.
Your code can now simply look like this:
sentence = []
while True:
entry = input("Enter a word: ")
if entry == "stop":
break
sentence.append(entry)
print(sentence)
You probably want something like this:
sentence = []
while True:
word = input("Enter a word: ")
if word == "stop":
break
sentence.append(word)
print " ".join(sentence) + "."

Categories

Resources