예제 #1
0
def multiScriptor(thing, qty, many_thresh=7):
    if qty == 0: return 'no {} '.format(inflect.plural(thing))
    for i in range(1, many_thresh + 1):
        if qty == i:
            return '{} {} '.format(inflect.number_to_words(i),
                                   inflect.plural(thing, count=i))
    return 'many {} '.format(inflect.plural(thing))
예제 #2
0
def makePlural(noun):
    # these words do not have plural forms
    if noun == "somebody" or noun == "something" or noun == "someone":
        return noun
    try:
        if getPOS(noun) == "singular":
            noun = inflect.plural(noun)
        return noun
    except:
        return noun
def getPluralDescription(text):
    tokens = nltk.word_tokenize(text)
    tokens = [w for w in tokens if not w.lower() in ['a', 'an']]
    tagged = nltk.pos_tag(tokens)

    chunk_rule = ChunkRule("<DT>?<JJ.?>?<NN>+", "Chunk nouns with determiner")
    chink_rule = ChinkRule("<DT>", "Remove Determiner")

    chunk_parser = RegexpChunkParser([chunk_rule], chunk_label="Singular Noun")
    chunked = chunk_parser.parse(tagged, trace=True)

    for subtree in chunked.subtrees(
            filter=lambda t: t.label() == 'Singular Noun'):
        subtree[-1:] = [(inflect.plural(subtree[-1][0]), "Plural")]
        break

    return tree2text(chunked)
예제 #4
0
 def filter_nouns(self, all_nouns):
     d = dict()
     numberAspects = 20
     Aspect_list_Filterd = []
     for i in range(len(all_nouns)):
         d[all_nouns[i]] = 0
     for j in range(len(all_nouns)):
         #if all_nouns[j] in d:
         d[all_nouns[j]] += 1
     for i in range(numberAspects):
         word = self.findMax(d)
         while inflect.plural(word) in Aspect_list_Filterd:
             del d[word]
             word = self.findMax(d)
         self.aspect_dict[word] = d[word]
         del d[word]
         Aspect_list_Filterd.append(word)
     return self.aspect_dict
예제 #5
0
 def getDesc(self) :
     scat, sdescriptors, gdescriptors, spnames, negatives, contains = self.scat, self.sdescriptors.copy(), self.gdescriptors.copy(), self.spnames.copy(), self.negatives.copy(), self.contains.copy()
     sdescriptors, gdescriptors, spnames, negatives, contains = self.ablateList(sdescriptors, rate=0.5), self.ablateList(gdescriptors, rate=0.3), self.ablateList(spnames, rate=0.6), self.ablateList(negatives, rate=0.75), self.ablateList(contains, rate=0.5)
     descriptors = sdescriptors + gdescriptors
     
     descs_pre = self.multiFormat(self.subSampleRemove(descriptors, 3)) if len(descriptors) > 0 else ''        
     if (len(contains) > 0 and rn.random() > 0.3) :
         parts_post = self.multiFormat(self.subSampleRemove(contains, at_most=2), prefix=' containing ', ensure_ending_and=True) if len(contains) > 0 else ''    
     else :
         parts_post =self.multiFormat(self.subSampleRemove(spnames, 3), prefix = rn.choice(self.combiners), ensure_ending_and=True ) if len(spnames) > 0 else ''                                
     descs_post= self.multiFormat(self.subSampleRemove(descriptors, 3), prefix = rn.choice(self.desc_prefixes), ensure_ending_and=True) if len(descriptors) > 0 else ''
     posts = [parts_post, descs_post]
     rn.shuffle(posts)
     output = 'a {}{}{}{}. '.format(descs_pre, scat, posts[0], posts[1])
     
     descs_r2 = self.multiFormat(descriptors[:5], prefix = ' it is ', ensure_ending_and=True) if len(descriptors) > 0 else ''
     parts_r2 = self.multiFormat(spnames[:5], prefix = ' it has ', ensure_ending_and=True) if len(spnames) > 0 else ''
     conts_r2 = self.multiFormat(contains, prefix = ' it contains ', ensure_ending_and=True) if len(contains) > 0 else ''
     
     round2 = []
     if len(descs_r2) > 0 : round2.append(descs_r2 + '. ')
     if len(parts_r2) > 0 : round2.append(parts_r2 + '. ')
     if len(conts_r2) > 0 : round2.append(conts_r2 + '. ')
     
     negs_descs = ''
     if len(negatives) > 0 :            
         negs_descs += 'it does not have '
         for thing in negatives :
             if 'a ' in thing :
                 negs_descs += '{} or '.format(thing)
             else :
                 negs_descs += 'any {} or '.format(inflect.plural(thing))
         negs_descs += '. '    
     if len(negs_descs) > 0 : round2.append(negs_descs) 
     
     rn.shuffle(round2)
     for thing in round2 :
         output += thing
     
     output = self.synReplace(output, chance=0.25)
     return self.fixDesc(output)
def pluralize_with(count, noun):
    """
    Pluralizes ``noun`` depending on ``count``.  Returns only the
    noun, either pluralized or not pluralized.

    Usage::

        {{ number_of_cats|pluralize_with:"cat" }}

        # Outputs::
        # number_of_cats == 0: "0 cats"
        # number_of_cats == 1: "1 cat"
        # number_of_cats == 2: "2 cats"

    Requires the ``inflect`` module.  If it isn't available, this filter
    will not be loaded.
    """
    if not inflect:
        raise ImportError('"inflect" module is not available.  Install using `pip install inflect`.')

    return str(count) + " " + inflect.plural(noun, count)
예제 #7
0
def pluralize_with(count, noun):
    """
    Pluralizes ``noun`` depending on ``count``.  Returns only the
    noun, either pluralized or not pluralized.

    Usage::

        {{ number_of_cats|pluralize_with:"cat" }}

        # Outputs::
        # number_of_cats == 0: "0 cats"
        # number_of_cats == 1: "1 cat"
        # number_of_cats == 2: "2 cats"

    Requires the ``inflect`` module.  If it isn't available, this filter
    will not be loaded.
    """
    if not inflect:
        raise ImportError('"inflect" module is not available.  Install using `pip install inflect`.')

    return str(count) + " " + inflect.plural(noun, count)
예제 #8
0
    if word in counter:
        del counter[word]

inflect = inflect.engine()

#for food in counter:
    #test if you can make the food singular, if it is already singular, will return false
    #if inflect.singular_noun(food) is False:
        #food = inflect.plural(food)
        #print(food)

pluralize_words = ["cocktail", "cookie", "strawberry", "raspberry", "grape", "cherry", "brownie", "tortilla", "sundae", "starburst", "peach", "oyster", "mushroom", "mashed potato", "jolly rancher", "hazelnut", "burrito", "banana"]

for word in pluralize_words:
    #if there is already a plural version of the word in the dictionary, get the value of the singular word and add it to the value of the plural word
    if inflect.plural(word) in counter.keys():
        counter[inflect.plural(word)] = counter[word] + counter[inflect.plural(word)]
        del counter[word]
    else:
        counter[inflect.plural(word)] = counter.pop(word)

counter["whipped cream"] = counter["whip cream"] + counter["whipped cream"]
del counter["whip cream"]


    #for food, count in counter.items():
        #if food == word:
            #counter[inflect.plural(word)] = counter.pop(food)

print("List of all the foods in the dictionary are:")
예제 #9
0
import inflect

inflect = inflect.engine()

foods = ["strawberries", "apple", "banana pancake", "pineapple"]

for food in foods:
    if inflect.singular_noun(food) is False:
        food = inflect.plural(food)
        print(food)
    else:
        print(food)

예제 #10
0
 def removeZeros(self):
     for child in reversed(self.children):
         if (child.quantity == 0):
             self.children.remove(child)
         child.removeZeros()
         if (child.quantity > 1): child.name = inflect.plural(child.name)
예제 #11
0
def isPluralForm(single, plural):
    return compareWords(inflect.plural(single), plural)
예제 #12
0
            ) + '/sentences'
            r = requests.get(url,
                             headers={
                                 'app_id': app_id,
                                 'app_key': app_key
                             })
            counter += 1

            data = json.dumps(r.json())
            data = json.loads(data)
            data = data["results"][0]

            sentences = [
                elem["text"] for elem in data["lexicalEntries"][0]["sentences"]
                if findWholeWord(word)(elem["text"].lower()) is not None
                or findWholeWord(inflect.plural(word))
                (elem["text"].lower()) is not None
            ]

            for s in sentences:
                char += len(s)

            if len(sentences) != 0:
                size = min(len(sentences), 4)
                sentences = sentences[:size]

            element["en"]["sentences"].append(sentences)

            french_sentences = client.translate(sentences,
                                                target_language='fr',
                                                source_language='en')
예제 #13
0
    #stop_counter variable to restrict number of generated sentences. optional.
    stop_counter = 0

    for i in perm:
        stop_counter += 1
        if (stop_counter == 30):
            break
        else:
            ran_names = random.sample(names, len(propernouns))
            '''loop checks for each word in the sentence whether its singular or plural form has a synonym in the permuted list and generates sentences with
				random names'''
            for word in text.split():

                if (inflect.singular_noun(word) is False):
                    plu = inflect.plural(word)
                    sing = word
                else:
                    plu = word
                    sing = inflect.singular_noun(word)
                plu = plu + "_"
                sing = sing + "_"
                # print(x)
                temp_str = [i[i.index(t)] for t in i if plu in t]
                x = plu
                if (not temp_str):
                    temp_str = [i[i.index(t)] for t in i if sing in t]
                    x = sing
                if (not temp_str):
                    if word in propernouns:
                        print(ran_names[propernouns.index(word)], end=' ')