Python,join() function, adding space between words - python

I need to write a function that takes two strings (text and word) and returns the text with the chosen word replaced with asterisks (the number of asterisks should correspond to the number of letters in the censored word.).
For example:
if text="hey hey hey" and word="hey" the returned text should be:
'*** *** ***'
Here is my code:
def censor(text,word):
text = text.split(" ")
asterisks=[]
text_with_asterisks=[]
for item in text:
if item not in word:
text_with_asterisks.append(item)
else:
asterisks=[]
for letter in word:
asterisks.append("*")
text_with_asterisks.append(' '.join(asterisks))
return (" ".join(text_with_asterisks))
The code works but it returns:
*********
and not
*** *** ***.
Once I use the line:
return ("_".join(text_with_asterisks))
instead I get:
'***_***_***'
I don't understand why the " " is ignored and how can I add a space between the words.
Thanks!

You have an extra space when you join your asterisks:
def censor(text, word):
text = text.split(" ")
asterisks=[]
text_with_asterisks=[]
for item in text:
if item not in word:
text_with_asterisks.append(item)
else:
asterisks=[]
for letter in word:
asterisks.append("*")
text_with_asterisks.append(''.join(asterisks)) #here's the culprit
return (" ".join(text_with_asterisks))
censor("hey hey hey", "hey") outputs what you want ('*** *** ***')
I just pointed out your mistake, but surely there's a more elegant and efficient way to do what you want.

Here is the simplest solution
text.replace(word, "*" * len(word))

Regex method of doing this -
import re
def censor(text,word):
return re.sub(r'\b(?i){0}\b'.format(re.escape(word)),'*' * len(word), text)
Example/Demo -
>>> censor('hey hey they hey','hey')
'*** *** they ***'
>>> censor('hey hey they Hey','hey')
'*** *** they ***'

You have spaces between every * in the word, and additional spaces between the words, so I think, you only want spaces between words:
def censor(text, word):
return ' '.join('*'*len(word) if word==item else item for item in text.split())

Simple solution,
>>> text = "hey hey hey"
>>> "***".join(text.split("hey"))
'*** *** ***'
Or
>>> text = "hey hey they Hey','hey"
>>> " ".join([ '***' if word.lower() == 'hey' else word
... for word in text.replace("'","").replace(","," ").split()])
'*** *** they *** ***'

As text_with_asterisks.append(' '.join(asterisks)) does, each character is joined by " ", and then " ".join(text_with_asterisks) also makes each words joined by " ", thus the output is: * * * * * * * * *, where there is a space between each star.

def censor(text, censor_w):
splitted_text = text.split(" ")
asterics = "*" * len(censor_w)
result = []
for word in splitted_text:
if word == censor:
result.append(asterics)
else:
result.append(word)
return " ".join(result)

Related

Can't figure out how to implement a tuple in a palindrome checker

So I'm learning python from a book, and I'm at the input/output section, in which it gives an example of code that checks for palindromes, but it only works for a word. After that it asks if I can improve the code by having a tuple contain the forbidden characters so that it can check if sentences like "Rise to vote, sir." are palindromes. I've been at it for a couple of time and I just can't wrap my head around how should I implement it.
The example code:
def reverse(text):
return text[::-1]
def is_palindrome(text):
return text == reverse(text)
something = input("Enter text: ")
if is_palindrome(something):
print("Yes, it is a palindrome")
else:
print("No, it is not palindrome")
What I've tried to do:
def reverse(text):
return text[::-1]
def sanitize(text):
text = text.lower
forbidden = (" ", ".", ",", "!", "?")
if forbidden in text:
text.replace(forbidden, "")
return text
something = input("Enter text: ")
def is_palindrome(text):
text = sanitize(text)
return text == reverse(text)
if is_palindrome(something):
print("Yes, it is a palindrome")
else:
print("No, it is not palindrome")
Of course this is wrong and throws out an error, but I've tried multiple attempts at it and I just can't figure it out, I'm sure the answer is really simple but I can't find
It might be more efficient (without using additional modules) to implement sanitize like this:
def sanitize(text):
forbidden = (" ", ".", ",", "!", "?")
tl = []
for c in text:
if not c in forbidden:
tl.append(c)
return ''.join(tl)
Of course, the forbidden variable could be a list, tuple or set.
Using a list comprehension is more concise but any difference in performance (either way) is likely to be marginal.
def sanitize(text):
return ''.join([c for c in text if c not in (" ", ".", ",", "!", "?")])
I found a few problems with your code.
text.lower should be changed to text.lower(). you should use a for loop to iterate through forbidden . And text should be updated to text.replace(c, “”) and c is each value in forbidden . This should be the code
def reverse(text):
return text[::-1]
def sanitize(text):
text = text.lower()
forbidden = (" ", ".", ",", "!", "?")
for c in forbidden:
text = text.replace(c, "")
return text
something = raw_input("Enter text: ")
def is_palindrome(text):
text = sanitize(text)
return text == reverse(text)
if is_palindrome(something):
print("Yes, it is a palindrome")
else:
print("No, it is not palindrome")

Manipulating list order

I am an artist taking a class on how to manipulate code to make poetry. Python was not supposed to be a prerequisite, but I am not getting it! Please help- we are supposed to make a snowball poem.
Here's the code I have so far:
my_string = "you're going home in a Chelsea ambulance"
counter = 0
new_list = my_string.split()
def make_a_snowball (text):
poem = ' '
for i in text:
poem = poem + "\n" + i
print (poem)
make_a_snowball (new_list)
The result is:
you're
going
home
etc..
I'd like it to look like:
you're
you're going
you're going home
etc...
Any suggestions? Help would be appreciated.
You just need to move the print method inside the loop:
my_string = "you're going home in a Chelsea ambulance"
counter = 0
new_list = my_string.split()
print(new_list)
def make_a_snowball(text):
poem = ' '
for word in text:
poem = poem + ' ' + word
print(poem)
make_a_snowball(new_list)
for i in range(len(new_list)):
print(poem.join(new_list[:i]))
If you want to have your whole poem be stored in one long string, here's how you'd do it:
def make_a_snowball(text):
poem_line = ''
full_poem = ''
for word in text:
poem_line += word + ' '
full_poem += poem_line + '\n'
print(full_poem)
return full_poem
This prints exactly what you want, except all at once rather than line-by-line.
The reason the code is printing each item on a new line is because we are inadvertantly adding a newline character between the terms, when we should be adding a space character.
In the following code, if we replace the \n with a " " and shift the print() function inwards so that it prints every time we loop through the items of the list, then this should work just fine.
my_string = "you're going home in a Chelsea ambulance"
counter = 0
new_list = my_string.split()
def make_a_snowball (text):
poem = ' '
for i in text:
poem = poem + " " + i
print (poem)
make_a_snowball (new_list)
This results in:
you're
you're going
you're going home
you're going home in
you're going home in a
you're going home in a Chelsea
you're going home in a Chelsea ambulance
A couple of additional thoughts.
In your code above, a counter is not necessary.
I like my code to be somewhat self descriptive, so I might replace this:
for i in text:
poem = poem + " " + i
print (poem)
with
for word in text:
poem = poem + " " + word
print (poem)

python:Move a specific word at the end of a string

i learn python and i do a discord bot. I have some difficulties to print the element after "anivia". i cant say if there is "anivia" in the 'texte' and i can count him but i don't know how to print the element after "anivia", if someone can help me please :)
#bot.command()
async def counter(ctx, *champion):
champion = " ".join(champion)
url = "https://u.gg/lol/champions/"
counter = "/counter"
uurl = url + champion + counter
await ctx.send(uurl)
import urllib.request
with urllib.request.urlopen(uurl) as response:
texte = response.read()
if ("anivia" in str(texte)):
print("Le mot existe !")
else:
print("Le mot n'existe pas!")
test = str(texte)
z = test.count('anivia')
print(z)
I can count 9 "anivia" with z and i want to print the next element after all the anivia (example: " hello i m anivia and i like anivia test": and, test).
Thanks for your help :)
If you're familiar with regular expressions (regex), this becomes very simple:
import re
# This pattern will capture the first word that comes after "anivia"
pattern = r'anivia (\w+)'
# Using this string as our example input
example_string = "anivia first anivia second and finally anivia third"
results = re.findall(pattern, example_string)
print(results) # Output: ['first', 'second', 'third']
Here is an approach that uses an auxiliary variable to mark when the next word needs to be printed.
test_string = "Hello, I am anivia on mid or anivia jungle"
do_print = False
splitted = test_string.split()
for word in splitted:
if do_print:
do_print = False
print(word)
if word == "anivia":
do_print = True
Output:
on
jungle
yeah, the those solution works with strings (i tried too with regex) but
do_print = False
splitted = test_string.split()
for word in splitted:
# print(word)
if do_print:
do_print = False
if word == "anivia":
do_print = True
test_string = str(texte)
do_print = False
splitted = test_string.split()
for word in splitted:
# print(word)
if do_print:
do_print = False
# print(word)
if word == "champion_id":
do_print = True``
on the first case i have the ("on" and the "jungle") but with my str(texte), that's doesn't fonction :S.
If someone knows why, the 2 test_strings are "strings"
^^ ty for your answers :)

'missing docstring' error, even though I have added them

def cat_latin_word(text):
"""converts the english into cat latin"""
constant = "bcdfghjklmnprstvwxyzBCDFGHJKLMNPQRSTVWXYZ"
result = []
for word in text.split():
if word[0] in constant:
word = (str(word)[1:] + str(word)[0] + "eeoow")
result.append(word)
elif word == "q":
word = ("oodbyegeeoow")
result.append(word)
else:
word = (str(word) + "meeoow")
result.append(word)
return ' '.join(result)
def cat_latin_from_sentence(text):
"""call the sub cat latin word sub function"""
return cat_latin_word(text)
def main():
"""Calling for the main function"""
text = input("Enter the english sentence: ")
print("cat latin =" + " "+ cat_latin_from_sentence(text))
I'm having to guess a bit here without you posting the actual Pylint message, but is it perhaps complaining that you're specifically missing a module docstring? That is, a docstring at the top of the file describing what the whole module is for, rather than the function-level docstrings that you have shown.

Python how to check if word is in list and in input?

I'm trying to get my program to go through an input sentence (e.g. "hello there!")
and see if any of the words in the input are in a list.
here is the code so far:
def findWholeWord(w):
return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search
i.upper() #i is the inputted variable as a string
WordsDocument = open('WordsDocument.txt').readlines()
for words in WordsDocument:
WordsList.append(words)
for word in i:
if findWholeWord(word) in WordsList:
print("Word Match")
Can someone help me develop a better solution / fix this so it works?
import re
def findWholeWord(w): # input string w
match_list = [] # list containing matched words
input_list = w.split(" ")
file = open('WordsDocument.txt', 'r')
text = file.read().lower()
file.close()
text = re.sub('[^a-z\ \']+', " ", text)
words_list = list(text.split())
for word in input_list:
if word in words_list:
print("Word Found: " + str(word))
match_list.append(word)
return match_list

Categories

Resources