0

I am trying to take an input as 'democracy is overrated.'and returns 'democr _acy is underrat_ed'

sentence= input()
suffixes = ["acy","tion", "ate",
            "er", "fy", "ize", "able", "ible", "al",
            "esque", "ful", "ic", "ous", "ish", "ive",
            "less", "ed"]
for pattern in suffixes :
    if pattern in sentence:
        out = ''
        par = sentence.partition(pattern)

        while par[1]:
                out += ' _'.join([par[0], par[1]])
                remainder = par[2]
                par = par[2].partition(pattern)
        sentence = ''.join([out, remainder])
print(''.join([out, remainder]))

as you can see my output is 'democr _acy is ov _err _at _ed.' I know that I have to search for a suffix at the end of the sentence and split into meaningful suffixes.To do that I thought sentence.endswith may work,but actually I am not sure how I can do this:(

0phase
  • 11
  • 2

3 Answers3

0
suffixes = ["acy","tion", "ate",
            "er", "fy", "ize", "able", "ible", "al",
            "esque", "ful", "ic", "ous", "ish", "ive",
            "less", "ed"]

def suffixize(sentence):
    words = []
    
    # Split the original sentence in spaces and iterate over each word
    for word in sentence.split(' '):
        # If this word ends with some suffix, return this suffix, else return None
        suffix = next((suffix for suffix in suffixes if word.endswith(suffix)), None)
  
        # If this word does not end with any suffix
        if suffix is None:
            # Leave it as it is
            words.append(word)
        else:
            # Remove the suffix from the word, append a _ and add the suffix
            words.append(f'{word[:-len(suffix)]}_{suffix}')

    # Join the words using a space
    return ' '.join(words)
    
print(suffixize("Democracy is overrated"))
# Output: 'Democr_acy is overrat_ed'

Note that this will not keep the spaces in the original input. This may or may not be what you want:

print(suffixize("Democracy        is       overrated"))
# Output: 'Democr_acy is overrat_ed'

To fix this, you can use the re module:

suffixes = ["acy","tion", "ate",
            "er", "fy", "ize", "able", "ible", "al",
            "esque", "ful", "ic", "ous", "ish", "ive",
            "less", "ed"]

import re

# Use named groups to differentiate between words and whitespace
pattern = re.compile(r'(?P<w>\w+)|(?P<s>\W+)')

def suffixize(sentence):
    tokens = []
    for match in pattern.finditer(sentence):
        word = match.group()
        
        # If it's a white-space
        if match.lastgroup == 's':
            # Just add to tokens
            tokens.append(word)
        else:
            # Do the suffix search
            suffix = next((suffix for suffix in suffixes if word.endswith(suffix)), None)
            if suffix is None:
                tokens.append(word)
            else:
                tokens.append(f'{word[:-len(suffix)]}_{suffix}')
            
    return ''.join(tokens)
    
print(suffixize("Democracy    is    overrated"))
# Output: 'Democr_acy    is    overrat_ed'
enzo
  • 9,861
  • 3
  • 15
  • 38
  • Thank you,I wonder what happened to the dot at the end.And if there was a comma in the middle for example 'Democracy, is overrated.' would it not come out in the output too? – 0phase Jun 19 '21 at 10:21
  • Do you think it would help to separate the punctuation marks from the word? @enzo – 0phase Jun 19 '21 at 10:26
  • @0phase I think the last snippet handles this well (e.g. it returns "Democr_acy, is overrat_ed." for "Democracy, is overrated."), but if there's an edge case let me know. – enzo Jun 19 '21 at 15:03
  • I am trying to do this without using any import,that's why I am complicated – 0phase Jun 19 '21 at 15:22
0

If suffixes is your list of suffixes then:

sentence = "democracy is overrated"

out = []
for word in sentence.split():
    for s in suffixes:
        if word.endswith(s):
            word = word[: len(word) - len(s)] + "_" + word[len(word) - len(s) :]
            break
    out.append(word)

print(" ".join(out))

Prints:

democr_acy is overrat_ed
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
  • thank you,I wonder what happened to the dot at the end.And if there was a comma in the middle for example 'Democracy, is overrated.' would it not come out in the output too? – 0phase Jun 19 '21 at 10:20
  • Do you think it would help to split the punctuation marks from the word? @Andrej Kesely – 0phase Jun 19 '21 at 10:27
0

Here's another way to do it without using imports:

suffixes = ["acy", "tion", "ate", "er", "fy", "ize", "able", "ible", "al", "esque", "ful", "ic", "ous", "ish", "ive", "less", "ed"]

def split_alpha(sentence):
    words = []
    
    # Create an alphabet with words
    alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    alphabet += alphabet.lower()
    
    # Store the current word being iterated
    current_word = None
    # Store if the current word is a alphabetical word
    is_alpha = False
    
    for char in sentence:
        is_current_alpha = char in alphabet
        
        # If a word is not defined yet
        if current_word is None:
            # Create a new word with the current char
            current_word = char
            is_alpha = is_current_alpha
    
        else:
            # If the current word has the same 
            # 'alphabeticity' of the current char 
            if is_current_alpha == is_alpha:
                current_word += char
            else:
                # Apprend the previous word to `words`
                words.append(current_word)
                
                # Create a new word with the current char
                current_word = char
                is_alpha = is_current_alpha
                
    if current_word is not None:
        words.append(current_word)
                
    return words

def suffixize(sentence):
    # Split the sentence into words
    words = split_alpha(sentence)
    
    # Split the original sentence in spaces and iterate over each word
    for word in words:
        # If this word ends with some suffix, return this suffix, else return None
        suffix = next((suffix for suffix in suffixes if word.endswith(suffix)), None)
  
        # If this word does not end with any suffix
        if suffix is None:
            # Leave it as it is
            words.append(word)
        else:
            # Remove the suffix from the word, append a _ and add the suffix
            words.append(f'{word[:-len(suffix)]}_{suffix}')

    # Join the words using a space
    return ' '.join(words)
    
assert split_alpha("abc") == ["abc"]
assert split_alpha("     ") == ["     "]
assert split_alpha("a1b2c3") == ["a", "1", "b", "2", "c", "3"]
assert split_alpha("hey there") == ["hey", " ", "there"]
assert split_alpha("democracy,   is overrated!") == ["democracy", ",   ", "is", " ", "overrated", "!"]

assert suffixize("Democracy is overrated") == 'Democr_acy is overrat_ed'
assert suffixize("democracy,   is overrated!") == 'democr_acy,   is overrat_ed!'
enzo
  • 9,861
  • 3
  • 15
  • 38