Given input:
Democr _acy , is overrat _ed .
Desired output:
Democracy, is overrated.
Here is my code:
sentence=input()
punctuation = "!\"#$%&'()*+,-./:;<=>?#[\]^`{|}~"
suffixes = ["acy", "ance", "ence", "dom", "er", "or", "ism", "ist",
"ty", "ment", "ness", "ship", "sion", "tion", "ate",
"en", "fy", "ize", "able", "ible", "al",
"esque", "ful", "ic", "ous", "ish", "ive",
"less", "ed", "ing", "ly", "ward", "wise"]
sentence_list = sentence.split('_')
c=""
if c not in punctuation:
print("".join(sentence_list))
elif c in punctuation:
for c in sentence:
print("".join(sentence_list).split(c))
As you can see my output has 29 different list but I just want one of them.
I want to remove '' from words and join punctuations and words which I removed '' from it.
When I write a code like:
sentence_list = sentence.split('_')
print("".join(sentence_list))
'_' and punctuations disseapear.Where am i doing wrong?
This is how I would tackle this problem.
def combineSentence(si):
punctuation = "!\"#$%&'()*+,-./:;<=>?#[\]^`{|}~"
rslt = ''
ptr = 0
while ptr < len(si):
if si[ptr] not in punctuation and si[ptr] != '_':
rslt += si[ptr]
else:
rslt = rslt[:-1]
if si[ptr] in punctuation:
rslt += si[ptr]
ptr += 1
return rslt
executing combineSentence('Democr _acy , is overrat _ed .') will yield:
'Democracy, is overrated.'
Related
Input = '12345678'
output = ['12','34','56','78']
I have to convert this Input string to output List as given above. please help to resolve this problem.
list1 = []
list1[0:2] = Input
print("list1..!", list1)
list2 = []
You could use re.findall for a regex option:
import re
inp = '12345678'
output = re.findall(r'\d{2}', inp)
print(output) # ['12', '34', '56', '78']
With simple slicing:
w = '12345678'
res = [w[i:i + 2] for i in range(0, len(w), 2)]
['12', '34', '56', '78']
An easier solution as you seem you are a beginner with python is;
input = '12345678'
str1 = ''
output = []
for i in input:
if len(str1) > 1:
output.append(str1)
str1 = ''
str1 += i
else:
str1 += i
if len(str1) > 1:
output.append(str1)
print(output)
Write the function which takes a string as input and return another string after
removing words that have characters repeated like-
Input : "This is an example"
Output : "This is an"
def string_oper(string):
if (len(string)==0):
return ''
if (set(string) == set(string[0])):
return ''
prev = None
letters = [l for l in string]
counter = 1
new = []
for l in letters:
if l==prev:
counter+=1
else:
if (counter==2):
new.append(prev)
counter=1
new.append(l)
prev = l
return ''.join(new)
# and then you can do:
string= string.fillna('').map(string_oper)
if __name__=='__main__':
string1 = input()
print(string_oper(string1))
I am getting this error-
File "C:\Users\ptane\Downloads\Day3\week2-new.py", line 24, in <module>
string= string.fillna('').map(string_oper)
^^^^^^
NameError: name 'string' is not defined
If I understand you correctly, you want to remove words from the string that have repeated characters (so example has two e, so remove it):
def remove_words(s):
return " ".join(word for word in s.split() if len(set(word)) == len(word))
s = "This is an example"
print(remove_words(s))
Prints:
This is an
This question already has answers here:
How to disemvowel a string with a condition where if the letter "g" is right beside a vowel, it would also be considered a vowel?
(3 answers)
Closed 3 years ago.
Working on a function that would detect if there are any vowels in a given string, also checks if the letter "g" is beside the vowels or not. If the letter "g" is beside a vowel, then it will also be considered a vowel. I did post a question similar to this and got an answer that almost works but I got no explanation as to how it was done and no-one replied to my comment asking for clarification.
Here is the function:
import re
def disemvowel(text):
result = re.sub(r"G[AEIOU]+|[AEIOU]+G|[AEIOU]+", "", text, flags=re.IGNORECASE)
print(result)
disemvowel("fragrance")
# frrnc
disemvowel('gargden')
# rgdn
disemvowel('gargdenag')
# rgdn
This function works for most cases except for when the letter 'g' both precedes and exceeds a vowel. For example, it does not work when I input 'gag' it returns 'g' when it isn't supposed to return anything. I just need clarification as to how this function works and what edits I could make to it to have it run properly for all scenarios.
This is my original function that I worked on but it only works for vowels since I could not figure out how to add a condition where it would detect the letter 'g' beside a vowel:
def disemvowel(text):
text = list(text)
new_letters = []
for i in text:
if i.lower() == "a" or i.lower() == "e" or i.lower() == "i" or i.lower() == "o" or i.lower() == "u":
pass
else:
new_letters.append(i)
print (''.join(new_letters))
disemvowel('fragrance')
# frgrnc
Two ways of doing it.
import re
def methodA(txt,ii):
vowels = ['a', 'e', 'i', 'o', 'u']
txt = re.sub('g'+ vowels[ii] +'g' ,' ', txt) # remove strings like gug
txt = re.sub(vowels[ii] + 'g', ' ', txt) # remove strings like ug
txt = re.sub('g' + vowels[ii] , ' ', txt) # remove strings like gu
if (ii == len(vowels)-1 or txt == '' or txt == ' ') : # if string is empty or all vowels have been used
txt = "".join( list(filter(lambda x:x not in ['a', 'e', 'i', 'o', 'u'], list(txt)))) # finally remove all vowels
txt = re.sub(' ', '', txt)
return txt
ii = ii + 1
return methodA(txt, ii) # call the function with next vowel in the list
ans = methodA("fragrance",0) # initialize with zeroth vowel
frrnc
from itertools import permutations
def methodB(txt):
vowels = ['a', 'e', 'i', 'o', 'u'] # vowels to remove
a = [] # store permutation of strings to remove in this list
for vowel in vowels: # create the list of all combo of characters that need to be removed
a.extend(list(map(lambda x : x[0]+x[1]+x[2] , list(permutations('g' + vowel + 'g')) )) )
a.extend(list(map(lambda x : x[0]+x[1] , list(permutations('g' + vowel )) )))
lims = list(set([re.sub('gg','', xx) for xx in a ])) # we don't need gg and the duplicates
lims.sort(key = len,reverse = True) # create a list of strings sorted by length
for ll in lims:
txt = re.sub(ll, ' ', txt) # remove the required strings with largest ones first
return re.sub(' ','',txt)
ans=methodB("fragrance")
frrnc
Here is a solution for this task:
def disemvowel(text):
return re.sub(r"G?[AEIOU]+G?", "", text, flags=re.IGNORECASE)
tests = {"fragrance": "frrnc", "gargden": "rgdn", "gargdenag": "rgdn", "gag": ""}
for test, value in tests.items():
assert disemvowel(test) == value
print("PASSED")
I want to replace these symbols with '-' and I know there should be a better way than doing this:
if '/' in var1:
var1= var1.replace('/', '-')
if '#' in var1:
var1= var1.replace('#', '-')
if ';' in var1:
var1 = var1.replace(';', '-')
if ':' in var1:
var1= var1.replace(':', '-')
This is what I tried, which is clearly wrong and I'm not able to properly optimize it.
str = 'Testing PRI/Sec (#434242332;PP:432:133423846,335)'
a = ['#',':',';','/']
print([str.replace(i,'-') for i in str])
replaceAll doesn't work, gives me an error saying str does not has that attribute.
str.replaceAll("[<>]", "")
How about using str.translate()?
# make a translation table that replaces any of "#:;/" with hyphens
hyphenator = str.maketrans({c: "-" for c in "#:;/"})
# use str.translate to apply it
print("Testing PRI/Sec (#434242332;PP:432:133423846,335)".translate(hyphenator))
Or, even faster, use a compiled regex:
compiled_re = re.compile("|".join(re.escape(i) for i in "#:;/"))
print(compiled_re.sub("-", "Testing PRI/Sec (#434242332;PP:432:133423846,335)"))
Both of these methods are much faster than the other methods proposed (at least on that input):
import re
import timeit
s = "Testing PRI/Sec (#434242332;PP:432:133423846,335)"
a = ["#", ":", ";", "/"]
hyphenator = str.maketrans({c: "-" for c in "#:;/"})
def str_translate():
s.translate(hyphenator)
def join_generator():
"".join("-" if ch in a else ch for ch in s)
def append_in_loop():
temp = ""
for i in s:
if i in a:
temp += "-"
else:
temp += i
def re_sub():
re.sub("|".join(re.escape(i) for i in a), "-", s)
def compiled_re_sub():
compiled_re.sub("-", s)
for method in [str_translate, join_generator, re_sub, append_in_loop, compiled_re_sub]:
# run a million iterations and report the total time
print("{} took a total of {}s".format(method.__name__, timeit.timeit(method)))
Results on my machine:
str_translate took a total of 1.1160085709998384s
join_generator took a total of 4.599312704987824s
re_sub took a total of 4.101858579088002s
append_in_loop took a total of 4.257988628000021s
compiled_re_sub took a total of 1.0353244650177658s
s = 'Testing PRI/Sec (#434242332;PP:432:133423846,335)'
a = ['#',':',';','/']
print(''.join('-' if ch in a else ch for ch in s))
Prints:
Testing PRI-Sec (-434242332-PP-432-133423846,335)
Or using re:
s = 'Testing PRI/Sec (#434242332;PP:432:133423846,335)'
a = ['#',':',';','/']
import re
print(re.sub('|'.join(re.escape(i) for i in a), '-', s))
Prints:
Testing PRI-Sec (-434242332-PP-432-133423846,335)
Use re package
import re
string = 'Testing PRI/Sec (#434242332;PP:432:133423846,335)'
result = re.sub('[#:;/]',"-", string)
print(result)
Result:
Testing PRI-Sec (-434242332-PP-432-133423846,335)
Just loop through add each character to the temp variable unless it is in the list "a" if it is in the list just replace it by adding "-" to the variable instead.
str = 'Testing PRI/Sec (#434242332;PP:432:133423846,335)'
a = ['#',':',';','/']
temp = ''
for i in str:
if i in a:
temp = temp + "-"
else:
temp = temp + i
print(temp)
For example :
Example 1:
string = "Jack and the bean stalk."
updated_string = "Jcak and the baen saltk."
Example 2:
string = "Hey, Do you want to boogie? Yes, Please."
updated_string = "Hey, Do you wnat to bogoie? Yes, Palsee."
Now this string is stored in a file.
I want to read this string from the file. And write the updated string back in the file at same positions.
Letters of each word of the string with length greater than 3 must be scrambled/shuffled while keeping first and last letter as it is. Also if there is any punctuation mark the punctuation mark stays as it is.
My approach:
import random
with open("path/textfile.txt","r+") as file:
file.seek(0)
my_list = []
for line in file.readlines():
word = line.split()
my_list.append(word)
scrambled_list =[]
for i in my_list:
if len(i) >3:
print(i)
s1 = i[1]
s2 = i[-1]
s3 = i[1:-1]
random.shuffle(s3)
y = ''.join(s3)
z = s1+y+s2+' '
print(z)
This is one approach.
Demo:
from random import shuffle
import string
punctuation = tuple(string.punctuation)
for line in file.readlines(): #Iterate lines
res = []
for i in line.split(): #Split sentence to words
punch = False
if len(i) >= 4: #Check if word is greater than 3 letters
if i.endswith(punctuation): #Check if words ends with punctuation
val = list(i[1:-2]) #Exclude last 2 chars
punch = True
else:
val = list(i[1:-1]) #Exclude last 1 chars
shuffle(val) #Shuffle letters excluding the first and last.
if punch:
res.append("{0}{1}{2}".format(i[0], "".join(val), i[-2:]))
else:
res.append("{0}{1}{2}".format(i[0], "".join(val), i[-1]))
else:
res.append(i)
print(" ".join(res))