So I have developed a code which lets you recreate a sentence but there is one problem,it cuts out a word! I don't know why so if somebody can correct it that would be brilliant thanks!
Sentence = input("Please enter a sentence: ")
Sen = Sentence.split()
remove=(",")
numbers = input("Enter Numbers(Separating them with a comma for example 1,3,2): ")
newnumbers = ""
for char in numbers:
if char not in remove:
newnumbers = newnumbers + char + " "
numlist = newnumbers.split()
length = len(numlist) -1
del numlist[length]
savenum = " ".join(numlist) -1
file = open("Bruh.txt","w")
file.write(Sentence)
file.write("\n"+savenum)
file.close()
newli = []
for char in numlist:
newnum = (int(char)-1)
newli = newli + [Sen[int(newnum)]]
words = " ".join(newli)
print("Original Sentence: ",Sentence)
print("Recreated Sentence: ", words)
These lignes are responsible for that behaviour :
# length = len(numlist) -1 # <==== comment these lines
# del numlist[length] # <==== comment these lines
Put them in comments, or remove them :
Sentence = input("Please enter a sentence: ")
Sen = Sentence.split()
remove=(",")
numbers = input("Enter Numbers(Separating them with a comma for example 1,3,2): ")
newnumbers = ""
for char in numbers:
if char not in remove:
newnumbers = newnumbers + char + " "
numlist = newnumbers.split()
# length = len(numlist) -1 # <==== comment these lines
# del numlist[length] # <==== comment these lines
savenum = " ".join(numlist) -1
file = open("Bruh.txt","w")
file.write(Sentence)
file.write("\n"+savenum)
file.close()
newli = []
for char in numlist:
newnum = (int(char)-1)
newli = newli + [Sen[int(newnum)]]
words = " ".join(newli)
print("Original Sentence: ",Sentence)
print("Recreated Sentence: ", words)
Related
def spin_words(sentence):
adjusted_string = sentence.split()
for i in adjusted_string:
if len(i) > 5:
print(i[::-1], end = ' ')
else:
print(i, end = ' ')
The problem is asking to take a string and return the same string but, with all the five letter words or more in reversed
def spin_words(sentence):
splitted_string = sentence.split()
reversed_fives = [s[::-1] if len(s) >= 5 else s for s in splitted_string]
return " ".join(reversed_fives)
Despite this fill-in-the-blank script working successfully, I am unsure of how to randomly assign blanks. As can be seen, I placed two blanks between 5-7. However, I would like to randomize where they're set.
sentence = """Immigration is an issue that affects all residents of the United States, regardless of citizenship status"""
sentence0 = sentence.split(" ")
max = len(sentence)
sentence1 = sentence0[0:5]
sentence1 = " ".join(sentence1)
sentence2 = sentence0[7:max]
sentence2 = " ".join(sentence2)
Overall = sentence1 + " _ _ " + sentence2
print(Overall)
test = input()
Overall2 = sentence1 + " " + test + " " + sentence2
print(Overall2)
start = "\033[1m"
end = "\033[0;0m"
if Overall2 == sentence:
print(start + "Correct" + end)
else:
print(start + "Incorrect" + end)
This is simple and is working :
import random
sentence = "Immigration is an issue that affects all residents of the United States, regardless of citizenship status"
words = sentence.split(" ")
#SELECT RANDOM WORD FOR PLACING BLANK
rand_index = random.randint(0, len(words)-1)
#KEEP A BACKUP OF THE WORD
word_blanked = words[rand_index]
#REPLACE WORD WITH BLANK
words[rand_index] = "_____"
#MAKE BLANKED SENTENCE AND CORRECT ANSWER
blanked_sentence = ""
correct_answer = ""
for word in words:
blanked_sentence = blanked_sentence + word + " "
if word == "_____":
correct_answer = correct_answer + word_blanked + " "
else:
correct_answer = correct_answer + word + " "
print(blanked_sentence)
answer = input("Enter your answer : ")
if answer == word_blanked:
print("Correct Answer!")
else:
print("Wrong Answer!")
print("Correct Answer is : ")
print(correct_answer)
Something like this:
import random
sentence = """Immigration is an issue that affects all residents of the United States, regardless of citizenship status"""
sentence0 = sentence.split(" ")
# removed overlap with "max"
max_length = len(sentence0)
# generate a random slice based on the length of the sentence.
random_slice = random.randrange(0, max_length)
sentence1 = sentence0[0:random_slice ]
sentence1 = " ".join(sentence1)
# increment two words forward from the random slice
sentence2 = sentence0[random_slice + 2: max_length]
sentence2 = " ".join(sentence2)
Overall = sentence1 + " _ _ " + sentence2
print(Overall)
test = input()
Overall2 = sentence1 + " " + test + " " + sentence2
print(Overall2)
start = "\033[1m"
end = "\033[0;0m"
if Overall2 == sentence:
print(start + "Correct" + end)
else:
print(start + "Incorrect" + end)
Generic example:
import random
sentence = 'The quick brown fox jumps over the lazy dog'
# convert sentence from string to list
sentenceList = sentence.split(' ')
# get random location of the element to be replaced
locToReplace = random.randrange(0, len(sentenceList))
# replace with blanks
sentenceList[locToReplace] = '_ _'
# convert back to string
updatedSentence = ' '.join(sentenceList)
print(updatedSentence)
I have a sequence of characters '-------' and i want to replace each '-' in it by each letter in 'jaillir' in the correct range.
How do i do that ?
Here is my code
import random
with open ("lexique.txt", "r", encoding= "utf8") as a:
words = []
letters = []
tirets= []
for line in a:
ligne = line[:-1]
words.append(ligne)
choix = random.choice(words)
tiret = ('-'* len(choix))
print(tiret)
print(choix)
accompli = False
while not accompli:
lettre = input("Entrez une lettre du mot ")
for t in range(len(tiret)):
if lettre in choix:
tiret.replace(tiret[t], lettre[t])
print(tiret)
I think you need to fix your file reading code, even though it is not the question, as below:
with open('lexique.txt', r) as f:
text = f.read() # get file contents
Next to replace the ---- by a word, I am assuming that the dashes in your text will only ever be the same length as the word, so:
word = 'word' # any string e.g. word
dashes = '-' * len(word)
So now you can use python's string.replace method like so:
text = text.replace(dashes, word) # every time it finds the sequence of dashes it will be replaced by your word
With a for loop (gradual replacement):
word = 'word' # any word
length = len(word)
temp = ''
for i, letter in enumerate(text):
if letter == '-':
if i + len(tempword) < len(text):
characters = [True if l == '-' else False for l in text[i:i + len(tempword)]]
if not(False in characters):
new += tempword[0]
if len(tempword) > 1:
tempword = tempword[1:]
else:
tempword = word
else:
new += letter
else:
new += letter
print(new)
I need to remove all excess white space and leave one space, between my words while only using if and while statements. and then state the amount of characters that have been removed and the new sentence
edit, it must also work for punctuation included within the sentence.
This is what I have come up with however it leaves me with only the first letter of the sentence i choose as both the number, and the final sentence. can anyone Help.
def cleanupstring(S):
lasti = ""
result = ""
for i in S:
if lasti == " " and i == " ":
i = ""
else:
lasti = i
result += i
return result
sentence = input("Enter a string: ")
outputList = cleanupstring(sentence)
print("A total of", outputList[1], "characters have been removed from your string.")
print("The new string is:", outputList[0])
Your code should be something like this:
def cleanupstring(S):
counter = 0
lasti = ""
result = ""
for i in S:
if lasti == " " and i == " ":
i = ""
counter += 1
else:
lasti = i
result += i
return result, counter
sentence = input("Enter a string: ")
outputList = cleanupstring(sentence)
print("A total of", outputList[1], "characters have been removed from your string.")
print("The new string is:", outputList[0])
The counter keeps track of how often you remove a character and your [0] and [1] work now the way you want them to.
This is because outputList is now a tuple, the first value at index 0 is now the result and the second value at index 1 is the counter.
How would I replace the spaces in a string with underscores without using the replace function. I was told to also use a accumulation string with some type of loop
string = input("Enter a string")
i = 0
acc = ""
for char in string:
if char == " ":
acc = string + "_"
print(acc)
Try this,
string = input("Enter a string")
i = 0
acc = ""
newlist = [] #create a new list which will be the output
strlist = list(string) #create a list of each character in the input string
for char in strlist:
if char == " ":
newlist.append('_')
newlist.append(char)
acc = ''.join(newlist)
print(acc)
Your code should to be :
string = input("Enter a string")
i = 0
acc = ""
for char in string:
if char == " ":
acc += "_"
else:
acc += char
print(acc)
Try it if without replace.
string = input("Enter a string")
res = ''.join(["_" if i == " " else i for i in string])
print(res)
Another method:
string = input("Enter a string")
res = "_".join(string.split(" "))
print(res)
Your code isn't too far off. You can use an accumulation string like this:
string = input("Enter a string")
acc = ""
for char in string:
if char == " ":
char = "_"
acc += char
print(acc)
If you are allowed to use split, then
s = 'Your string with spaces'
s_ = ''
for word in s.split():
s_ += '_' + word
s_[1:] # 'Your_string_with_spaces'
Otherwise, instead of words, concatenate characters with '_' instead of ' ':
s_ = ''
for char in s:
if char == ' ':
s_ += '_'
else:
s_ += char