Replacing strings while keeping punctuation - python-2.7

I have a task to write a program that replaces words like Noun, Place, PluralNoun etc.. with the word "corgi". I got the code 90% right but I'm missing the punctuation but I don't know why. Here is the code I wrote:
parts_of_speech = ["PLACE", "PERSON", "PLURALNOUN", "NOUN"]
test_string = """This is PLACE, no NOUN named PERSON, We have so many PLURALNOUN around here."""
def word_in_pos(word, parts_of_speech):
for pos in parts_of_speech:
if pos in word:
return word
return None
def play_game(ml_string, parts_of_speech):
replaced =[]
word=ml_string.split(" ")
for w in word:
print w
con = word_in_pos(w,parts_of_speech)
if con != None:
replaced.append(w.replace(con,"corgi"))
else:
replaced.append(w)
return " ".join(replaced)
print play_game(test_string, parts_of_speech)

word_in_pos() is returning the argument word in its entirety, including any punctuation in it. So when you do your replace(), you're also replacing the punctuation. Instead, just return pos from word_in_pos():
def word_in_pos(word, parts_of_speech):
for pos in parts_of_speech:
if pos in word:
return pos
return None
Result:
This is corgi, no corgi named corgi, We have so many corgi around here.

Related

Regex differentiate between all vs few char Uppercase in String

I have to pass a string into a program, depending on the string, it will return only one response value. I am facing difficulty in building patterns for two cases.
If a string ends with '?' and is not all uppercase return 'x', no matter what the contents of string.
If a string end with '?' and is all uppercase return 'y'.
If a string ends with '!' , or is all uppercase (no question mark at end) return 'z'.
If a string is only whitespace return 'a'.
Here are two example strings, they are to be four separate patterns -
phrase1 = "Simple String with some UPPercase in Between ends with?"
phrase2 = "BIG STRING ALL CAPS ENDS WITH?"
phrase3_a = "ALLCAPSSTRING NOTHING AT THE END OF STRING"
phrase3_b = "Any String with ALL UPPERCASE (or not) but ends with!"
phrase4 = "\t\t\t\t"
I haven't built accurate patterns, and that's what I'm asking here. After that I plan to use a single re.compile with all patterns & then finditer to use the group which is not None. In code below, I have removed the whitespaces,since if none of the other patterns match, matching a whitespace pattern [\s] will return None, which I can use separetely-
phrase=re.sub(r'[\s]','',phrase)
pattern_phrase1 = re.compile (r'[a-zA-Z0-9]\?$')
pattern_phrase2 = re.compile (r'[A-Z0-9]\?$')
pattern_phrase3 = re.compile (r'[A-Z]|[.!$]')
Solution 1 - using isx functions
def hey(phrase):
responses ={'ques':x,'ques_yell':y,'yell':z,'onlycall':b,'what':c}
phrase=''.join(phrase.split())
if phrase=='':
return responses['onlycall']
if phrase.isupper():
if phrase[-1]=='?':
return responses['ques_yell']
return responses['yell']
elif not phrase.isupper():
if phrase[-1]=='?':
return responses['ques']
return responses['what']

letter changer lowercase to uppercase(vice versa) : Whats wrong in my code?

I wanted to enter a word with upperandlower letter combination letters and then when i press enter it will change vice versa
def changer(word):
for letter in word:
if letter.isupper():
letter.lower()
elif letter.islower():
letter.upper()
print word
word = raw_input()
changer(word)
You must append the converted letters to new string, and returning the new string could be helpful, too.
def changer(word):
newWord = ""
for letter in word:
if letter.isupper():
newWord += letter.lower()
elif letter.islower():
newWord += letter.upper()
print newWord
return newWord
...you do not return anything. and strings in python are immutable; you can not change them in-place.
this is something you could try:
def swapcase(word):
return ''.join(c.lower() if c.isupper() else c.upper() for c in word)
print(swapcase(word='Hello')) # hELLO
where i use str.join to join the generator that iterates over the characters with the swapped case.
speed-wise str.translate may be the better choice:
from string import ascii_lowercase, ascii_uppercase
trans_table = str.maketrans(ascii_lowercase + ascii_uppercase,
ascii_uppercase + ascii_lowercase)
def swapcase(word):
return word.translate(trans_table)
print('Hello'.translate(trans_table)) # hELLO

Python - How to replace spaces in simple line of text with a specific character

I am looking for some help in reformatting a line of text, from within a python script, so that I can replace certain characters with others, or spaces with a specific character. For clarity, the text I am trying to reformat is assigned to a variable.
I have searched for this feature but I have not seen how this can be done!
I have tried to write a full function for you to fit your purpose:
def posSubStringReplaceRecursively(string1, search, replace, pos, is_First):
global string2
if is_First:
string2 = list(copy.deepcopy(string1))
is_First = False
index = str.rfind(string1, search)
if index != -1:
string1 = string1[:(index+len(search)-1)]
pos.append(index)
return posSubStringReplaceRecursively(string1, search, replace, pos, is_First)
else:
pos = pos
for i in xrange(len(pos)):
string2[pos[i]:pos[i]+len(search)] = replace
string2 = " ".join(string2)
return string2
Calling the function:
string1 = raw_input("Enter string:\n")
search = raw_input("Enter word to find:\n")
replace = raw_input("Enter word to replace:\n")
print posSubStringReplaceRecursively(string1, search, replace, [], True)

converting a list to string and printing it out python

I am trying to convert the first letter of each word of a string to uppercase in python. But i keep getting a generator object at 0x10315b8> no post before this seems to answer my question.
def capitalize(str):
newstr = str.split(' ')
newlist = []
for word in newstr:
if word[0][0] == word[0][0].upper():
newlist.append(word[0][0].upper())
newlist.append(word[0][1:])
newlist.append(" ")
convert_first = (str(w) for w in newlist)
print(convert_first)
capitalize(input("enter some string"))#calling the function
Your problem lies in how you are trying to make a string out of a list of strings. The opposite of "splitting" a string into a list is "joining" a list into a string.
def capitalize(str):
newstr = str.split(' ')
newlist = []
for word in newstr:
newlist.append(word[0].upper() + word[1:])
convert_first = ' '.join(newlist)
print(convert_first)
capitalize(input("enter some string"))#calling the function
Note: I made an attempt to have my code be as close as possible to that in the question.
Also, why is there an if statement in your code? With that in place you're really just capitalizing all the words that are already capitalized and discarding the rest since they never make it into newlist.
There are a few issues with your code:
The error message you got is for trying to print convert_first, which is a generator, not a string.
newstr is a list of words, so word is a string and word[0] is already the first character. Meaningless for word[0][0] or word[0][1:].
if word[0][0] == word[0][0].upper(): just filters all the words whose first character is not uppercase...
So simply some code will do what you described:
def capitalize(str):
newstr = str.split(' ')
newlist = []
for word in newstr:
newlist.append(word[0].upper())
newlist.append(word[1:])
newlist.append(" ")
convert_first = ''.join(w for w in newlist)
print(convert_first)
capitalize(input("enter some string"))
Or those who favors short code and generator expressions:
def capitalize(str):
print(' '.join(word[0].upper() + word[1:] for word in str.split(' ')))
capitalize(input("enter some string"))
This also removes the tailing space of the generated string, which may (not) be what you intended.

perform join python returns a "none"

my "output" seems to populate fine however when I perform the join I get "none returned.
Any ideas?
def englishify_sentence(s):
"""English"""
words = s.lower()
words = words.split()# splits sentence into individual words
output = []
for i in range(len(words)):
if words[i].endswith("way"):
opt1 = words[i][:-3]
letters = list(opt1)#breaks given word into individual letters
translate = ("("+opt1+" or "+"w"+opt1+")")
output.append(translate)
else:
opt2 = words[i][:-2]
opt2_letters = list(opt2)#breaks given word into individual letters
first_letter = (opt2_letters.pop(-1))
opt3 = words[i][:-3]
translate2 = (first_letter+opt3)
output.append(translate2)
english = " ".join(output)#removes speech marks and creates a "real" word
print(output)
english = englishify_sentence("oday ouyay antway anway eggway")
print(english)
You forgot to return the value.
return english
Is it the print(output) that's giving you a none or the print(english)?