예제 #1
0
    def count_one_concept(self, concept, document_text):
        record = []

        # '(' ,')'是正则表达式中的元字符,所以要把查询pattern中的'('替换为'\('
        concept = concept.replace('(', '\(').replace(')', '\)')
        # 处理单复数匹配
        word_pages_fre = [len(re.findall(r'\b({}|{})\b'.format(
            concept, pluralize(concept)), text)) for text in document_text]
        word_pages = []
        for i, num in enumerate(word_pages_fre):
            record.extend([i+1]*num)

        record.extend(word_pages)
        frequency = Counter(record)
        return frequency
예제 #2
0
def inject_nn_error(example):
    tok_sentence, features_seq = example[0].split(), example[1]
    noun_indices = []
    for i in range(len(features_seq)):
        if features_seq[i]['universal_postag'] == 'NOUN':
            noun_indices.append(i)

    if len(noun_indices) > 0:
        j = random.choice(noun_indices)
        singular_form = pattern.singularize(tok_sentence[j])
        plural_form = pattern.pluralize(tok_sentence[j])
        if tok_sentence[j] != singular_form:
            tok_sentence[j] = singular_form
        elif tok_sentence[j] != plural_form:
            tok_sentence[j] = plural_form
    else:
        return None
    return [' '.join(tok_sentence), features_seq]
예제 #3
0
def convert_postag(complex_word, candidates):
    specific_tag = NLP.pos_tag(complex_word)[0][1]
    generic_tag = get_type(specific_tag)
    # print(generic_tag)
    final_candidates = set()
    if generic_tag == "NN":  ### Nouns
        # print(generic_tag)
        for candidate in candidates:
            candidate_tag = NLP.pos_tag(candidate)[0][1]
            if specific_tag == "NNS" and candidate_tag != "NNS":
                candidate = pluralize(candidate)
                # print("pluraaal  ", candidate)
            elif specific_tag == "NN" and candidate_tag == "NNS":
                candidate = singularize(candidate)
            final_candidates.add(candidate)
    elif generic_tag == "ADJ":  ## Adjectives
        for candidate in candidates:
            candidate_tag = NLP.pos_tag(candidate)[0][1]
            if specific_tag == "JJR" and candidate_tag != "JJR":
                candidate = comparative(candidate)
            elif specific_tag == "JJS" and candidate_tag != "JJS":
                candidate = superlative(candidate)

            final_candidates.add(candidate)
    elif generic_tag == "VB":  ## Verbs
        complex_tense = tenses(complex_word)
        if (len(complex_tense)) < 1: return candidates

        for candidate in candidates:
            if len(tenses(candidate)) > 0 and tenses(
                    candidate)[0][0] != complex_tense:
                if complex_tense == "past":
                    candidate = conjugate(candidate, tense=PAST)
                elif complex_tense == "present":
                    candidate = conjugate(candidate, tense=PRESENT)
                elif complex_tense == "future":
                    candidate = conjugate(candidate, tense=FUTURE)
                elif complex_tense == "infinitive":
                    candidate = conjugate(candidate, tense=INFINITIVE)
            final_candidates.add(candidate)
    else:
        final_candidates = candidates

    return final_candidates
예제 #4
0
def get_words(dict):
    keys = list(dict.keys())
    random.shuffle(keys)

    # Loop inspired by Austin Marshall on Stack Overflow
    # https://stackoverflow.com/questions/7785672/how-to-iterate-through-dict-in-random-order-in-python
    for key in keys:
        while dict[key] == "" and key != "NOUN_2P":
            if key.startswith("A"):
                dict[key] = input("Please input an " + get_type(key) + ": ")
            else:
                dict[key] = input("Please input a " + get_type(key) + ": ")

            if dict[key] == "":
                print("I didn't get that. Please try again")

    # Special modifications of other words
    dict["NOUN_2P"] = pluralize(dict["NOUN_2"])
    dict["VERB_1P"] = conjugate(dict["VERB_1"], "p")
예제 #5
0
def add_single_plural(text, tokenizer):
    tokens = tokenizer.tokenize(text)
    vocab = tokenizer.get_vocab()
    contains = []
    for word in vocab:
        if word.isalpha() and len(word) > 2:
            for t in tokens:
                if len(t) > 2 and word != t and (word.startswith(t) or t.startswith(word)):
                    contains.append(word)

    for t in tokens[:]:
        if not t.isalpha():
            continue
        sig_t = singularize(t)
        plu_t = pluralize(t)
        if sig_t != t and sig_t in vocab:
            tokens.append(sig_t)
        if plu_t != t and plu_t in vocab:
            tokens.append(plu_t)
    return [w for w in tokens + contains if w not in STOPWORDS]
예제 #6
0
def index():
    """Display the home page for generating ideas"""
    key = UNSPLASH_API_KEY
    idea = ""
    with open('words/base.txt') as f:
        bases = f.readlines()
    with open('words/noun.txt') as f:
        nouns = f.readlines()

    base = choice(bases)
    noun = pluralize(choice(nouns).strip())
    idea = f"{base} but for {noun}"

    params = {
        "client_id": key,
        "query": noun,
    }

    r = requests.get("https://api.unsplash.com/photos/random/", params=params)
    img = json.loads(r.content)

    return render_template('index.html', idea=idea, img=img)
    def try_fix_form(word_pos, syn_pos):
        word = word_pos[0]
        syn = syn_pos[0]
        pos_tag_word = word_pos[1]
        pos_tag_syn = syn_pos[1]

        if pos_tag_syn != pos_tag_word:
            # Check if its only plural version
            if pos_tag_word == pos_tag_syn + 'S':
                if pos_tag_syn.startswith('J'):
                    return en.superlative(syn)
                elif pos_tag_syn.startswith('N'):
                    return en.pluralize(syn)
            return None if pos_tag_syn[:2] != pos_tag_word[:2] else syn
        else:
            if not pos_tag_syn.startswith('V'):
                return syn
            # We check if verb is in correct form
            default_conjugator = mlconjug.Conjugator(language='en')

            if pos_tag_word == 'VB':
                return default_conjugator.conjugate(
                    syn).conjug_info['indicative']['indicative present']['1s']
            elif pos_tag_word == 'VBG':
                return default_conjugator.conjugate(syn).conjug_info[
                    'indicative']['indicative present continuous']['1s 1s']
            elif pos_tag_word == 'VBN':
                return default_conjugator.conjugate(syn).conjug_info[
                    'indicative']['indicative present perfect']['1p']
            elif pos_tag_word == 'VBP':
                return default_conjugator.conjugate(
                    syn).conjug_info['indicative']['indicative present']['1s']
            elif pos_tag_word == 'VBZ':
                return default_conjugator.conjugate(
                    syn).conjug_info['indicative']['indicative present']['3s']
            elif pos_tag_word == 'VBD':
                return default_conjugator.conjugate(syn).conjug_info[
                    'indicative']['indicative past tense']['1s']
예제 #8
0
def has_many(model_name, **relation_kwargs):
    """Connect children to parent in one-to-many relationship.

    class Parent:
        children = relationship("Child", back_populates="parent")
    """
    singular_model_name = singularize(model_name)
    caller_namespace, db, table_name, caller_table_name, caller_class_name = rip_context_info(
        singular_model_name)
    plural_variable_name = pluralize(table_name)
    singular_class_name = to_class_name(singular_model_name)

    caller_namespace[f'{plural_variable_name}'] = db.relationship(
        f'{singular_class_name}',
        back_populates=f'{caller_table_name}',
        **relation_kwargs)

    try:
        callback = global_relations[caller_table_name][table_name]
    except KeyError:
        callback = None

    if callback:
        callback(plural_variable_name)
        def write_hypo(parent, count, list_of_neighbors):

            return_dict = {}

            for index in range(0, len(list_of_neighbors)):
                s = wordnet.synsets(list_of_neighbors[index])
                if len(s) > 0:
                    s = s[0]

                    synomyms = s.synonyms
                    hypernyms = s.hypernyms()
                    hyponyms = s.hyponyms()
                    holonyms = s.holonyms()
                    meronyms = s.meronyms()
                    singulars = [singularize(list_of_neighbors[index])]
                    plurals = [pluralize(list_of_neighbors[index])]
                    comparatives = [comparative(list_of_neighbors[index])]
                    superlatives = [superlative(list_of_neighbors[index])]
                    lemmas = [lemma(list_of_neighbors[index])]
                    lexemes = [lexeme(list_of_neighbors[index])]
                    tensess = [tenses(list_of_neighbors[index])]
                    suggests = [suggest(list_of_neighbors[index])]

                    neighbors_with_link_string = None

                    if parent in synomyms:
                        neighbors_with_link_string = str(
                            list_of_neighbors[index]) + "[SYNO]"
                    elif parent in hypernyms:
                        neighbors_with_link_string = str(
                            list_of_neighbors[index]) + "[HYPER]"
                    elif parent in hyponyms:
                        neighbors_with_link_string = str(
                            list_of_neighbors[index]) + "[HYPO]"
                    elif parent in holonyms:
                        neighbors_with_link_string = str(
                            list_of_neighbors[index]) + "[HOLO]"
                    elif parent in meronyms:
                        neighbors_with_link_string = str(
                            list_of_neighbors[index]) + "[MERO]"
                    elif parent in singulars:
                        neighbors_with_link_string = str(
                            list_of_neighbors[index]) + "[PLURAL]"
                    elif parent in plurals:
                        neighbors_with_link_string = str(
                            list_of_neighbors[index]) + "[SINGULAR]"
                    elif parent in comparatives:
                        neighbors_with_link_string = str(
                            list_of_neighbors[index]) + "[COMPA]"
                    elif parent in superlatives:
                        neighbors_with_link_string = str(
                            list_of_neighbors[index]) + "[SUPERLA]"
                    elif parent in lemmas:
                        neighbors_with_link_string = str(
                            list_of_neighbors[index]) + "[LEMMA]"
                    elif parent in lexemes:
                        neighbors_with_link_string = str(
                            list_of_neighbors[index]) + "[LEXEME]"
                    elif parent in tensess:
                        neighbors_with_link_string = str(
                            list_of_neighbors[index]) + "[TENSE]"
                    elif parent in suggests:
                        neighbors_with_link_string = str(
                            list_of_neighbors[index]) + "[MISPELL]"

                    if neighbors_with_link_string:
                        try:
                            return_dict[word][1].append(
                                neighbors_with_link_string)
                        except:
                            return_dict[word] = (count,
                                                 [neighbors_with_link_string])
            return return_dict
예제 #10
0
def main():
    start_time = time.time()

    qpage = str(
        raw_input("Enter a recipe link from AllRecipes website: ")).strip()
    while not 'https://' in qpage or requests.get(qpage).status_code != 200:
        qpage = str(
            raw_input(
                "Invalid link - Enter a recipe link from AllRecipes website again: "
            )).strip()

        # Ask for a user input
    transformation = str(
        raw_input(
            "What type of transformation do you want to do to the recipe?\n Your options are vegetarian, nonvegetarian, vegan, nonvegan, healthy, unhealthy, altmethod, easy, chinese, italian: "
        ))

    options = [
        'vegetarian', 'nonvegetarian', 'vegan', 'nonvegan', 'healthy',
        'unhealthy', 'altmethod', 'easy', 'chinese', 'italian'
    ]
    if transformation in options:
        print 'Transforming to ' + transformation + '...\n'
    else:
        print ' Your option(' + transformation + ') is not available. Analyzing original recipe...\n'

    # Scrape necessary lists: including units, primary cooking methods, other cooking methods, tools, meat,vegetable
    mod = 'html.parser'

    # scrape units
    unit_page = 'https://www.adducation.info/how-to-improve-your-knowledge/units-of-measurement/'
    unit_sp = prep.Scraper(unit_page, mod)
    units = unit_sp.scrape_unit()

    # scrape primary cooking methods:
    primarycookingmethods_page = 'https://www.thedailymeal.com/cook/15-basic-cooking-methods-you-need-know-slideshow/slide-12'
    primarycookingmethods_sp = prep.Scraper(primarycookingmethods_page, mod)
    primarycookingmethods = primarycookingmethods_sp.scrape_primarycookingmethods(
    )
    primarycookingmethods = [
        pc for pc in primarycookingmethods if not 'fry' in pc
    ]
    primarycookingmethods.append('fry')

    # scrape other cooking methods:
    othercookingmethods_page = 'https://www.d.umn.edu/~alphanu/cookery/glossary_cooking.html'
    othercookingmethods_page_sp = prep.Scraper(othercookingmethods_page, mod)
    othercookingmethods = othercookingmethods_page_sp.scrape_cookingmethods()

    # scrape tools.txt
    tools_page = 'tools.txt'
    tools_sp = prep.Scraper(tools_page, '')
    tools = tools_sp.scrape_tools()

    # VEGETARIAN
    # scrape meat
    meat_page = "http://naturalhealthtechniques.com/list-of-meats-and-poultry/"
    meatlist_sp = prep.Scraper(meat_page, mod)
    meatList = meatlist_sp.scrape_meats()
    meatList.extend(("pepperoni", "salami", "proscuitto", "sausage", "ham",
                     "chorizo", "rib", "steak", "bone", "thigh"))

    seafood_page = "https://en.wikipedia.org/wiki/List_of_types_of_seafood"
    seafoodlist_sp = prep.Scraper(seafood_page, mod)
    seafoodList = seafoodlist_sp.scrape_seafood()
    meatList.extend(seafoodList)

    meatSubs = [
        ingred.tofu, ingred.tempeh, ingred.texturedvegprote, ingred.mushrooms,
        ingred.jackfruit, ingred.lentils
    ]
    commonMeatList = [
        "chicken", "pork", "beef", "lamb", "salmon", "tuna", "duck", "turkey",
        "ham"
    ]
    # VEGAN
    veganSubs = {
        "milk": ingred.almondmilk,
        "cream": ingred.almondmilk,
        "yogurt": ingred.coconutyogurt,
        "egg": ingred.silktofu,
        "butter": ingred.soymarg,
        "honey": ingred.agave,
        "cheese": ingred.nutyeast,
        "gelatin": ingred.agar
    }

    # Healthy Substitutions
    unhealthySubsDict = {
        "turkey": ingred.beef,
        "chicken": ingred.breadedchicken,
        "fish": ingred.beef
    }
    healthySubsDict = {
        "sugar": ingred.sugar,
        "bacon": ingred.turkeybacon,
        "bread": ingred.wholegrainbread,
        "bread crumb": ingred.rolledoats,
        "butter": ingred.fatfreebutterspread,
        "cream": ingred.halfandhalf,
        "cream cheese": ingred.fatfreecreamcheese,
        "egg": ingred.eggwhites,
        "flour": ingred.wholewheatflour,
        "beef": ingred.leanbeef,
        "lettuce": ingred.arugula,
        "mayonnaise": ingred.reducedfatmayo,
        "evaporated milk": ingred.evaporatedskim,
        "milk": ingred.fatfreemilk,
        "rice": ingred.brownrice,
        "dressing": ingred.fatfreedressing,
        "sour cream": ingred.fatfreesourcream,
        "chocolate chip": ingred.unsweetenedchips
    }

    # Alt Methods
    altList = []
    pm_list = []
    # Simmer, Stew, and Braise too situational
    br = "broil"
    bake = "bake"
    sr = "sear"
    gr = "grill"
    rt = "roast"
    f = "fry"
    sa = "saute"
    st = "steam"
    any = "any"
    altMethods = []
    altMethods.append(prep.AltCook("meat", bake, [br, rt, gr, sr, f]))
    altMethods.append(prep.AltCook("meat", br, [bake]))
    altMethods.append(prep.AltCook("meat", sa, [bake, f]))
    altMethods.append(prep.AltCook("meat", sr, [bake, gr, rt, f]))
    altMethods.append(prep.AltCook("meat", gr, [bake, sr, rt, f]))
    altMethods.append(prep.AltCook("meat", rt, [bake, sr, gr, f]))
    altMethods.append(prep.AltCook("veg", any, [st]))

    vegetable_page = "https://simple.wikipedia.org/wiki/List_of_vegetables"
    vegetableList_sp = prep.Scraper(vegetable_page, mod)
    vegetableList = vegetableList_sp.scrape_vegtables()

    # CUISINE TRANSFORMATION LISTS
    commonSpices = [
        "salt", "pepper", "garlic powder", "onion powder", "water", "butter",
        "olive oil", "oil"
    ]

    commonSauces = [
        "barbecue", "bbq", "gravy", "buffalo", "tabasco", "sriracha",
        "mustard", "ketchup", "salsa"
    ]
    commonOils = [
        "canola oil", "vegtable oil", "coconut oil", "peanut oil", "lard",
        "cooking spray"
    ]

    typicalSpices = [
        ingred.salt, ingred.pepper, ingred.garlicpowder, ingred.onionpowder
    ]

    # Chinese Ingredients
    chineseSpices = [
        ingred.ginger, ingred.star_anise, ingred.five_spice, ingred.cilantro,
        ingred.chinesecinnamon, ingred.cloves, ingred.fennelseed,
        ingred.corianderseed, ingred.chilipowder, ingred.peppercorn
    ]
    chineseSauces = [
        ingred.fishsauce, ingred.soysauce, ingred.oystersauce,
        ingred.chilipaste
    ]
    chineseVegetables = {
        "bell pepper": ingred.whiteradish,
        "asparagu": ingred.bambooshoots,
        "pea": ingred.beanspouts,
        "lettuce": ingred.bokchoy,
        "brussel sprout": ingred.chives,
        "kale": ingred.chinesecabbage
    }
    chineseIngredients = [chineseSpices, chineseSauces, chineseVegetables]

    # Italian Ingredients
    italianSpices = [
        ingred.oregano, ingred.thyme, ingred.rosemary, ingred.sage,
        ingred.basil, ingred.marjoram
    ]

    italianSauces = [
        ingred.tomatosauce, ingred.alfredosauce, ingred.pestosauce
    ]

    italianOils = [ingred.oliveoil]

    italianIngredients = [italianSpices, italianSauces, italianOils]

    # scrape recipe
    recp = prep.Scraper(qpage, mod)
    ingredients = recp.scrape_ingredients()
    directions = recp.scrape_directions()

    prepIngredients = []

    # Parse ingredients
    for igd in ingredients:
        prepIngredients.append(prep.Ingredients(igd, units))

    # Parse directions
    primary_cookingmethods_list = []
    other_cookingmethods = []
    used_tools = []
    steps_time = []

    for dir in directions:
        direction = prep.Directions(dir, primarycookingmethods,
                                    othercookingmethods, tools)
        if direction.primaryMethods:
            primary_cookingmethods_list.append(direction.primaryMethods)
        if direction.tools:
            used_tools.append(direction.tools)
        if direction.otherMethods:
            other_cookingmethods.append(direction.otherMethods)
        if direction.cookingtime:
            steps_time.append(direction.cookingtime)

    # analyze ingredients in each step for toAltMethods
    stepIngredients = []
    igd_for_dir = set([
        ing.name for ing in prepIngredients for word in ing.name.split(' ')
        if word in directions[0]
    ])
    stepIngredients.append(igd_for_dir)
    for i in range(1, len(directions)):
        igd_for_dir = set([
            ing.name for ing in prepIngredients for word in ing.name.split(' ')
            if word in directions[i]
        ])
        if len(igd_for_dir) < 1:
            stepIngredients.append(stepIngredients[i - 1])
        else:
            stepIng = ', '.join(igd_for_dir)
            stepIngredients.append(stepIng.split(', '))

    # Transform Ingredient List based on input
    primary_cookingmethods = [
        item for sublist in primary_cookingmethods_list for item in sublist
        if not item is 'none'
    ]
    if transformation == "vegetarian":
        prepIngredients, directions = toVegetarian(prepIngredients, meatList,
                                                   meatSubs, directions)
    elif transformation == "nonvegetarian":
        prepIngredients, directions = toNonVegetarian(prepIngredients,
                                                      commonMeatList, meatSubs,
                                                      directions)
    elif transformation == "vegan":
        prepIngredients, directions = toVegan(prepIngredients, meatList,
                                              meatSubs, veganSubs, directions)
    elif transformation == "nonvegan":
        prepIngredients, directions = toNonVegan(prepIngredients,
                                                 commonMeatList, meatSubs,
                                                 veganSubs, directions)
    elif transformation == "easy":
        prepIngredients, directions = toEasy(prepIngredients, commonSpices,
                                             typicalSpices, directions)
    elif transformation == "healthy":
        prepIngredients, directions = toHealthy(prepIngredients,
                                                healthySubsDict, directions)
    elif transformation == "unhealthy":
        prepIngredients, directions = toUnhealthy(prepIngredients,
                                                  healthySubsDict,
                                                  unhealthySubsDict,
                                                  directions, seafoodList)

    elif transformation == "altmethod":
        count1 = 0
        for pm in primary_cookingmethods_list:
            altmethods_list, directions, org_method = toAltMethod(
                stepIngredients[count1], vegetableList, meatList, altMethods,
                pm, directions)
            altList.append(altmethods_list)
            pm_list.append(org_method)
            count1 += 1
    elif transformation == "chinese":
        prepIngredients, directions = toChinese(prepIngredients,
                                                chineseIngredients,
                                                commonSpices, commonSauces,
                                                directions)
    elif transformation == "italian":
        prepIngredients, directions = toItalian(prepIngredients,
                                                italianIngredients,
                                                commonSpices, commonSauces,
                                                commonOils, directions)

    # Steps: analyze each direction
    steps = []
    all_altermethod = []
    for i in range(len(directions)):
        igd_for_dir = set([
            ing.name for ing in prepIngredients for word in ing.name.split(' ')
            if word in directions[i]
        ])
        if len(igd_for_dir) < 1:
            igd_for_dir = ['none']
        alttxt = ""
        if altList and altList[i][0] != "":
            alttxt = "Alternate Cooking Method: " + pm_list[
                i] + ' --> ' + ', '.join(altList[i])
            all_altermethod.append(pm_list[i] + ' --> ' +
                                   ' ,'.join(altList[i]))
            alttxt += ' | '
        steps.append('Step ' + str(i + 1) + ': | ' + 'Ingredients: ' +
                     ', '.join(set(igd_for_dir)) + ' | ' + 'Tools: ' +
                     ', '.join(set(used_tools[i])) + ' | ' +
                     'Primary Cooking Methods: ' +
                     ', '.join(set(primary_cookingmethods_list[i])) + ' | ' +
                     alttxt + 'Other Cooking Methods: ' +
                     ', '.join(set(other_cookingmethods[i])) + ' | ' +
                     'Time: ' + ', '.join(steps_time[i]) + ' | ' +
                     'Details/Directions: ' + directions[i])

    # Output: transformed ingredients
    print 'Ingredients:'
    for ingredient in prepIngredients:
        print 'name: ' + ingredient.name
        print 'quantity: ' + str(ingredient.quantity)
        print 'measurement: ' + ingredient.measurement if ingredient.quantity <= 1 or ingredient.measurement is 'none' \
            else 'measurement: ' + pluralize(ingredient.measurement)
        print 'descriptor: ' + ingredient.descriptor
        print 'preparation: ' + ingredient.preparation
        print '\n'

    # Output: tools
    used_tools = [
        item for sublist in used_tools for item in sublist
        if not item is 'none'
    ]
    print 'Tools:\n', ', '.join(
        set(used_tools)) if len(used_tools) > 0 else 'none'

    # Output: methods
    print '\nMethods:'
    print '\tPrimary cooking methods:', ', '.join(set(primary_cookingmethods)) \
        if len(primary_cookingmethods) > 0 else 'none'
    if transformation == "altmethod":
        if all_altermethod:
            print "\tAlternate Cooking Methods: " + ', '.join(
                set(all_altermethod))
        else:
            print "\tAlternate Cooking Methods: No alternate cooking method is available for this recipe."

    other_cookingmethods = [
        item for sublist in other_cookingmethods for item in sublist
        if not item is 'none'
    ]
    print '\tOther cooking methods:', ', '.join(
        set(other_cookingmethods)) if len(other_cookingmethods) > 0 else 'none'

    # Output: steps
    print '\nSteps:'
    for s in steps:
        print '\n'.join(s.split(' | '))
        print '\n'

    recipe_title = recp.scrape_title()

    # HTML Output: transformed ingredients
    f = open("results.html", "w")
    f.write("<html><body><h1>" + recipe_title + "</h1><br/>")
    f.write("<h2>Ingredients:</h2><br/>")
    for ingredient in prepIngredients:
        if str(ingredient.quantity) != "none":
            f.write(str(ingredient.quantity) + " ")
        else:
            f.write("")
        if ingredient.measurement is 'none':
            f.write("")
        elif ingredient.quantity <= 1:
            f.write(" " + ingredient.measurement)
        else:
            f.write(" " + pluralize(ingredient.measurement))
        f.write(" " + ingredient.name + "<br/>")
        # f.write('descriptor: ' + ingredient.descriptor + "<br/>")
        # f.write('preparation: ' + ingredient.preparation + "<br/><br/>")

    # HTML Output: tools
    f.write('<h2>Tools:</h2><br/>')
    f.write(', '.join(set(used_tools)) if len(used_tools) > 0 else 'none')
    f.write('<br/>')
    # HTML Output: methods
    f.write('<br/><h2>Methods:</h2><br/>')
    f.write('Primary cooking methods: ')
    f.write(', '.join(set(primary_cookingmethods)
                      ) if len(primary_cookingmethods) > 0 else 'none')
    f.write("<br/>")
    if transformation == "altmethod":
        if all_altermethod:
            f.write("Alternate Cooking Methods: " +
                    ', '.join(set(all_altermethod)))
            f.write("<br/>")
        else:
            f.write(
                "Alternate Cooking Methods: No alternate cooking method is available for this recipe."
            )
            f.write("<br/>")
    f.write('Other cooking methods: ')
    f.write(', '.join(set(other_cookingmethods)
                      ) if len(other_cookingmethods) > 0 else 'none')

    # HTML Output: steps
    f.write('<h2>Steps:</h2><br/>')
    for s in steps:
        f.write('<br/>'.join(s.split(' | ')))
        f.write('<br/><br/>')

    # Calculate running time
    end_time = time.time()
    print 'Running time: ' + str(end_time - start_time)
예제 #11
0
async def main(websocket, path):
    await websocket.send("Hello, My name is Zoro and I am here to help! :)")
    print("> Hello, My name is Zoro and I am here to help! :)")
    context = None
    while True:
        try:
            user_input = await websocket.recv()
            print(f"< {user_input}")
        except ConnectionClosedError:
            print("< Client close connection")
            break
        except ConnectionClosedOK:
            print("< Client close connection")
            break
        user_input_tok = nltk.word_tokenize(user_input)
        skip_logic = False
        exit_loop = False
        for word in user_input_tok:
            if word.lower() in ("thank", "you", "thanks"):
                await websocket.send(
                    "You are welcome, If you need further assistance I will be here to help!"
                )
                print(
                    "> You are welcome, If you need further assistance I will be here to help!"
                )
                skip_logic = True
                exit_loop = True
                break
            elif word.lower() in ("hello", "hi"):
                await websocket.send("Hi, good day to you!")
                print("> Hi, good day to you!")
                await websocket.send("How may I help you today?")
                print("> How may I help you today?")
                skip_logic = True
                break
        if skip_logic and exit_loop:
            break
        elif skip_logic:
            continue
        parsed_input = rephrase(user_input, mappings)
        if is_question(parsed_input):
            product = identify_product(parsed_input)
            if isinstance(product, str):
                line_split = product.split(".")
                line1 = line_split[0] + "."
                line2 = line_split[1] + "."
                await websocket.send(line1)
                print(f"> {line1}")
                await websocket.send(line2)
                print(f"> {line2}")
                context = None
            elif product is not None:
                context = product
                cleaned = clean_sentence(parsed_input)
                ans = answer(cleaned, product, general=False)
                await websocket.send(ans)
                print(f"> {ans}")
            elif product is None and context is not None:
                for word, tag in nltk.pos_tag(
                        nltk.word_tokenize(parsed_input)):
                    if tag == "PRP":
                        cleaned = clean_sentence(parsed_input)
                        ans = answer(cleaned, context, general=False)
                        await websocket.send(ans)
                        print(f"> {ans}")
            # print(cleaned)
            elif product is None and context is None:
                if "products" in nltk.word_tokenize(parsed_input):
                    products_type = get_stored_attrs()["products"]
                    seen = {}
                    dupes = []
                    for x in products_type:
                        if x not in seen:
                            seen[x] = 1
                        else:
                            if seen[x] == 1:
                                dupes.append(x)
                            seen[x] += 1
                    for x in dupes:
                        products_type.remove(x)
                    for i, x in enumerate(products_type):
                        products_type[i] = pluralize(x)
                    products_str = ", ".join(products_type)
                    products = get_stored_attrs()["title"]
                    random_product = []
                    for x in range(0, 3):
                        random_product.append(random.choice(products))
                    products_t_str = ", ".join(random_product)
                    await websocket.send(f"We sell {products_str}")
                    print(f"> We sell {products_str}")
                    await websocket.send(
                        f"Some of the products we sell are {products_t_str}.")
                    print(
                        f"> Some of the products we sell are {products_t_str}."
                    )
                else:
                    await websocket.send(
                        "Sorry I do not understand your question")
                    print("> Sorry I do not understand your question")
                    await websocket.send(
                        "You may contact our support team by opening a new request for assistance"
                    )
                    print(
                        "> You may contact our support team by opening a new request for assistance"
                    )
            else:
                await websocket.send(
                    "Sorry, I can only answer questions regarding the products we sell."
                )
                print(
                    "> Sorry, I can only answer questions regarding the products we sell."
                )
                await websocket.send(
                    "You may contact our support team by opening a new request for assistance"
                )
                print(
                    "> You may contact our support team by opening a new request for assistance"
                )
        else:
            await websocket.send(
                "Sorry, I can only answer questions regarding the products we sell."
            )
            print(
                "> Sorry, I can only answer questions regarding the products we sell."
            )
            await websocket.send(
                "You may contact our support team by opening a new request for assistance"
            )
            print(
                "> You may contact our support team by opening a new request for assistance"
            )
예제 #12
0
def gen_root_name(root_name):
    return pattern.pluralize(root_name)
from pattern.text.en import conjugate, lemma, lexeme
print(lemma('gave'))
print(lexeme('gave'))

from pattern.text.en import pluralize, singularize

print(pluralize('leaf'))
print(singularize('theives'))
print(singularize('words'))

from pattern.text.en import comparative, superlative

print(comparative('good'))
print(superlative('good'))

from pattern.text.en import suggest

print(suggest("Whitle"))
print(suggest("white"))
print(suggest("assid"))
예제 #14
0
def convert_index_name(file_name):
    name_split = file_name.split('_')
    name_split[-1] = pluralize(name_split[-1])
    return '_'.join(name_split)