Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I wanted to include spaces too while splitting the text, for that i looked up on google used import re
import re
def censor(text,word) :
text1=re.split(r"(\s+)",text)
#print text1
sum=""
for i in range(0,len(text1)) :
if text1[i]==word :
for j in range(0,len(word)) :
sum=sum+"*"
else :
sum=sum+text[i]
return sum
The error I am getting is
image displaying error and code
If I include an another for loop to replace every 'e' with a whitespace , it doesn't work.
In your code, text1 (very bad naming BTW) is a list of words, and text a single string. Your first for loop is iterating on text1 indices (words in the list), but in the else clause you subscript the whole text string. Obviously you want to get the word from the words list (text1), not the character at position i in the text string. IOW: replace your else clause with:
sum=sum+text1[i]
and the test should pass.
If you used a correct naming and proper code layout you would certainly have spotted the problem more easily:
def censor(text, word) :
words = re.split(r"(\s+)",text)
sum=""
for i in range(0, len(words)) :
if words[i] == word :
for j in range(0, len(word)) :
sum = sum + "*"
else :
# here you easily spot the error
sum = sum + text[i]
return sum
Also you are making things much more complicated than they have to be. You can pre-compute the "replacement" string for "bad" words once for all before the loop (and you don't need a loop to do so), and you don't need a range and indexed acces, ou can iterate directly on the words list instead:
def censor(text, word) :
replacement = "*" * len(word)
words = re.split(r"(\s+)", text)
cleaned = ""
for w in words :
if w == word :
cleaned += replacement
else :
cleaned += w
return cleaned
There would be other possible improvements but at least this is mostly readable and much more pythonic.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 10 months ago.
Improve this question
I'm trying to write a simple program where it removes the previous letter when there exists a "/" after the character. Also, if there are two "//" after two characters, it should remove the last two characters. The number of / only exists if there a similar number of characters before so // in this scenario: aa//.
for example
x = 'abc/c/dd//a'
print x.rstrip('/')
it should return
aba
another example
x = '/aab//'
print x.rstrip('/')
should return
a
I have seen solutions trying the method above, but it doesn't seem to work for me. Is there an optimal solution for this?
A simple function can do this :
def stripStr(x, special_char="/"):
buff = ""
for char in x:
if char == special_char:
buff = buff[:-1]
else:
buff += char
return buff
assert stripStr('abc/c/dd//a') == 'aba'
assert stripStr('abc////cde/dd///a') == 'ca'
The idea is to reconstruct the string (in the buff variable) character after character. You simply need to keep appending each char except when you find a / then you have to remove the last char of the string.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
currently I faced issue with python code
I have two questions relate with "def" code.
1)
I need to print out 6 alphabet which is "K,E,Y,S,N,O"
slimier like under sample
enter image description here
2)
how can I print out this alphabet if user typing one word like "KEY" then print out *mark with KEY
or If user typing "BED" then print out "E"only because we only have alphabet with K,E,Y,S,N,O
if can anyone help me with this two questions? I appreciate that
Thanks
Question 1 need work with 2-dimensional list (list with lists for rows) and I skip this problem.
As for Question 2 you can filter chars in word.
You can treat string "BED" as list of chars (even without using list("BED")) and you can use it in for-loop to check every char with list ["K","E","Y","S","N","O"] (or "KEYSNO") and skip chars "B" and "D"
#my_chars = "KEYSNO" # also works
my_chars = ["K","E","Y","S","N","O"]
word = "BED"
for char in word:
if char in my_chars:
print(char, "- OK")
else:
print(char, "- unknown")
Result:
B - unknown
E - OK
D - unknown
This way you can create new list to keep only correct chars
my_chars = ["K","E","Y","S","N","O"]
word = "BED"
filtered_chars = []
for char in word:
if char in my_chars:
filtered_chars.append(char)
print(filtered_chars)
Result:
['E']
In Python you can write it even shorter using list comprehension
filtered_chars = [char for char in word if char in my_chars]
Eventually you can write it with function filter() like
filtered_chars = list(filter(lambda char: char in my_chars, word))
This question already has answers here:
Check if string appears as its own word - Python
(4 answers)
How to replace multiple substrings of a string?
(28 answers)
Closed 4 years ago.
I want to replace the word 'I' in a sentence by the word 'you', and many other such examples. This is not that difficult, except that the 'I' in a word like 'Instagram' is now also being replaced - which I do not want. I would expect this is very simple but cannot find the solution (I am still inexperienced in programming). Here is my code.
s = 'I can increase my number of Instagram followers'
i = s.split()
i = [i.replace('I', 'you') for i in i]
i = [i.replace('my', 'your') for i in I]
i = " ".join(i)
This gives:
You can increase your number of younstagram followers.
But how do you get this result?
You can increase your number of Instagram followers.
EDIT
I have changed the title of the question
FROM: How to find a word in a string that is not part of another word? Python.
TO: How to replace a word in a sentence ONLY IF that word appears on its own and is not part of another word? Python
This question was marked as a duplicate of Check if string appears as its own word - Python.
However, the answers there only seem to check if a given word appears in a sentence as its own word (not as part of another word) and return a boolean. However, knowing that may be a necessary condition but is not a sufficient condition for replacing that word by something else – which is my goal. Therefore, my question may not be a duplicate of the question it is now linked with.
The following would be simple solutions, but do not work:
i = [i.replace(' I ' , 'you') for i in i] # white space left and right of 'I'
i = [i.replace('''I''', 'you') for i in i]
Any suggestions how to solve this problem?
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
The task is:
Given a string, return a new string where the first and last chars have been exchanged.
def front_back(str):
if len(str)<=0:
return str
else:
front=str[0]
back=str[-1]
new = str.replace(str[0], back)
print new
new_2=new.replace(new[-1], front)
print new_2
front_back("code")
Why?
It won't work because .replace() will replace all occurrences of that character, not necessarily only the first and last
Below is a solution that constructs the string with first, body and last portions
text = 'code'
first, body, last = text[0], text[1:-1], text[-1]
result = last + body + first
# 'eodc'
String literals can be sliced and added:
>>> s = "hello world"
>>> s[-1] + s[1:-1] + s[0]
'dello worlh'
P.S. str is a builtin in python, so using it as a variable name is a bad idea.
First, never call a variable str. Why? Because that is the name of the class for Python strings. If you use the same name then you loose it. I use txt.
Your test with the length is sensible, but the lower limit can be increased (a single character would be silly).
But using str.replace() is not feasible. Why? Well it could work in your test case, but only because each character is unique. str.replace() replaces every occurrence of the specified string. So if the first or last character was repeated elsewhere then that would be changed as well.
You can use slicing, where the first (leftmost) character is 0 (zero). You can also index from the right using negative numbers, so -1 is the last (rightmost) character. The range of characters goes from the start to the character after the last. So [1:-1] goes from the second character to the last but one.
def front_back(txt):
if len(txt) <= 1:
return txt
else:
new_txt = txt[-1] + txt[1:-1] + txt[0]
return new_txt
print front_back("code")
I use return in the function, since that would be the normal way of processing text, and that is asked for in your question.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 months ago.
Improve this question
I have this code:
mylist = open('sortedwords.txt')
txt = mylist.read()
mylist = txt.split()
stuff = input('Type a word here: ')
def removeletters (word, Analysis):
for char in range (len(Analysis)):
if Analysis [char] in word:
word = word.replace(Analysis[char],"",1)
return word
def anagramSubset(word, textList):
newWord = word
for char in range(len(textList)):
if textList[char] not in newWord:
return False
else:
newWord = newWord.replace(textList[char],"",1)
return True
def anagram(word, textList):
savedWords =[]
for checkword in textList:
if len(word) == len(checkword) and anagramSubset(word, checkword):
savedWords.append(checkword)
print(checkword)
anagram(stuff, mylist)
It is supposed to take an input word, remove letters from the input word, then make a subset of words and save that to an array to print off of.
The problem is that the code will save every word that can be created from the input. E.g. an input of spot results in top, tops, stop, pots, pot, etc. The result should only have tops, pots, and stop.
What is wrong with the code, and how do I fix it?
I looked at the code and am wondering what the recursion is adding? The first pass does all of the computational work and then the recursion adds some extra stack frames and alters how output is printed. Am I making the wrong assumption that textList is a list of valid words split from a single line in a file?
When I run this locally with a particular word list, this gets the same effect (in the sense that it finds words whose letters are a subset) with less thrashing:
def anagram(word, textList):
savedWords = []
for checkword in textList:
if anagramSubset(word, checkword):
savedWords.append(checkword)
print(savedWords)
If the problem eventually becomes that you're getting words that have too few letters, you could fix your problem by checking that a word is the length of the original word before you add it with:
if len(original_word) == len(checkword):
savedWords.append(checkword)