def postMaker():
    url = "https://api.telegram.org/<bot-key>/sendMessage"

    tags = input("\nTags: ")
    if tags.find('-') >= 0:
        return chalk.red("\nText has a hyphen!\n")
    else:
        description = input("Description: ")

        # TODO - add conditional check for if the URL is working
        link = input("Link: ")

    data = {
        "chat_id": "<Chat-id>",
        "text":
        f"<b>Tags:</b> {tags}\n\n<b>Description:</b> {description}\n\n<b>Link:</b> {link}",
        "parse_mode": "html"
    }

    # Send a post request to the bot's API
    response = requests.post(url, data)

    # Check if there's an error
    if response.status_code == 200:
        return chalk.green("\nThe post has been sent successfully!\n")
    else:
        return chalk.red("\nSomething wrong has happened\n")
Example #2
0
def changeFileName():
    try:
        print(chalk.cyan("Example: \n\n File Path: ./myfolder/pepe/file \n Rename to: ./myfolder/pepe/file2 \n\n"))
        fileDir = input("File Path: ")
        renameTo = input("Rename to: ")
        if fileDir != renameTo:
            os.rename(fileDir, renameTo)
            return chalk.green.bold("\nFile got renamed!")
        else:
            return chalk.red("\nFile names are similar. Please use a different name")
    except FileNotFoundError:
        return chalk.red("\nFile not found!")
Example #3
0
def start_quiz(questions):
    score = 0
    for i in range(0, len(questions)):
        print(questions[i]["question"] + "\n")
        for j in range(1, 5):
            print(str(j) + " " + questions[i]["option" + str(j)])
            print()
        try:
            answer = int(input())
        except ValueError:
            print(chalk.cyan('Please enter a choice between 1 and 4\n'))

            continue
        print()
        if 0 < answer < 5:
            if (questions[i]["correct_answer"] == "option" + str(answer)):
                print(chalk.green("Correct Answer!!!\n"))
                score = score + 1
            else:
                correct_answer = questions[i]["correct_answer"]
                print(
                    chalk.red("Wrong!! The Correct Answer is {}".format(
                        questions[i][correct_answer])))
                print()
        else:
            print(chalk.yellow("Invalid Choice\n"))

    print(chalk.yellow("Your Score is {}/{}".format(score, len(questions))))
Example #4
0
def handle_confirmation(update, context):
    action_by = update.message.chat.username
    action_type = context.user_data['fund_action']
    fund_manager = context.user_data['fund_manager']
    amount = context.user_data['amount']
    try:
        print(
            'fund transaction successful',
            chalk.blue(
                create_fund_transaction(fund_manager,
                                        amount,
                                        action_type,
                                        datetimeCreated=datetime.now(),
                                        action_by=action_by)))
    except Exception as e:
        print(
            chalk.red(
                "Error in fund handle_confirmation, cannot create fund_transaction"
            ))
        del context.user_data['fund_manager']
        del context.user_data['amount']
        del context.user_data['fund_action']
        return handle_fund_menu(update, context)
    try:
        if action_type == 'withdraw':
            TransactionHandler.createTransaction(fund_manager, 'fund', amount,
                                                 'fund withdrawal',
                                                 datetime.now())

        if action_type == 'deposit':
            TransactionHandler.createTransaction('fund', fund_manager,
                                                 amount, 'fund deposit',
                                                 datetime.now())
    except Exception as e:
        # clear context
        del context.user_data['fund_manager']
        del context.user_data['amount']
        del context.user_data['fund_action']
        message = f'Transaction fail! Error in updating fundDB.'
        update.message.reply_text(message)
        print(
            Chalk.red(
                'Error in fund handle_confirmation, cannot update transaction DB'
            ))
        return handle_fund_menu(update, context)

    try:
        balance = check_fund_balance()
        message = f'Transaction Successful! Current fund balance/amount in circulation: {balance}'
        # Respond success
        update.message.reply_text(message)
        return handle_exit_to_main(update, context)
    except Exception as e:
        message = f'Transaction fail! Error in reading balance.'
        update.message.reply_text(message)
        del context.user_data['fund_manager']
        del context.user_data['amount']
        del context.user_data['fund_action']
        print("Cannot read balance balance")
Example #5
0
def handle_show_history(update, context):
    username = update.message.chat.username

    try:
        transactions = retrievePastTransactions(username)
        message = "Last 5 Transactions:\n=================================\n"

        for transaction in transactions:
            message += format_transaction(username, transaction)
            message += "\n"
        # Respond success
        update.message.reply_text(message)
        return handle_exit_to_main(update, context)

    except Exception as e:
        print(chalk.red("ERROR: handle_show_balance"))
        print(chalk.red(e))
Example #6
0
 def get_summary(errorCount: int, warningCount: int) -> str:
     summary = ''
     if errorCount:
         summary += chalk.red(f'{errorCount} errors')
     if warningCount:
         summary = f'{summary} and ' if summary else ''
         summary += chalk.yellow(f'{warningCount} warnings')
     return summary
Example #7
0
def handle_show_balance(update, context):
    username = update.message.chat.username

    try:
        balance = checkRunningBalance(username)
        message = f'Current balance: {balance}'
        # Respond success
        update.message.reply_text(message)
        return handle_exit_to_main(update, context)

    except Exception as e:
        print(chalk.red("ERROR: handle_show_balance"))
        print(e)
def findSoilphWordInSentences(lemmatizedSentences, plantName, category,
                              wikiLink):
    soilPH = False
    with open('plantSoilphData.csv', 'a', newline='') as csvfile:
        writer = csv.writer(csvfile)
        for sentence in lemmatizedSentences:
            for word in sentence:
                if (word == 'ph' or word == 'pH' or word == 'PH'):
                    print(chalk.green.bold('Soil pH found for'), plantName)
                    soilPH = True
                    containsoilph = " ".join(str(x) for x in sentence)
                    # print(containsoilph,'\n')
                    # filterdSentence = tokenizer.tokenize(containsoilph)
                    # containsoilph = " ".join(str(x) for x in filterdSentence)
                    # print("plant Name is :" ,plantName, containsoilph);
                    for value in containsoilph:
                        containsoilph = containsoilph.replace('-', ' ')
                        containsoilph = containsoilph.replace('ā€“', ' ')

                    # print(containsoilph)
                    doc = nlp(containsoilph)
                    count = 0
                    min = 999
                    max = 0.0
                    for token in doc:
                        if token.like_num:
                            try:
                                value = float(token.text)
                                if min == 999:
                                    min = value
                                else:
                                    min = value if value < min else min

                                max = value if value > max else max
                            except ValueError:
                                pass

                    writer.writerow([
                        plantName, category, 'pH', min, max, wikiLink,
                        containsoilph, ''
                    ])
                    print(min, max, plantName)

    if (soilPH == False):
        print(chalk.red("No Soil pH for "), plantName)
        with open('plantSoilphData.csv', 'a', newline='') as csvfile:
            writer = csv.writer(csvfile)
            writer.writerow(
                [plantName, category, 'x', 'x', 'x', wikiLink, 'x'])
Example #9
0
    def download_track(self, track_data):
        try:
            meta_data = self.match_track_with_spot_meta_data(track_data)
            if meta_data is None:
                meta_data = self.match_track_with_spot_meta_data(
                    track_data,
                    search_term=__create_alternate_search_term__(track_data))
                if meta_data is None:
                    print('unable to download song ' + track_data['name'])
                    return
            url = 'https://music.youtube.com/watch?v=' + meta_data['id']
            ydl_opts = {
                'format':
                'bestaudio/best',
                'outtmpl':
                '~/Music/' + meta_data['title'] + '.%(ext)s',
                'progress_hooks': [self.my_hook],
                'quiet':
                True,
                'no_warnings':
                True,
                'postprocessors': [{
                    'key': 'FFmpegExtractAudio',
                    'preferredcodec': 'mp3',
                    'preferredquality': '0',
                }]
            }
            with YoutubeDL(ydl_opts) as ydl:
                ydl.download([url])

            audiofile = eyed3.load(
                str(Path.home()) + '/Music/' + meta_data['title'] + '.mp3')
            if audiofile.tag is None:
                audiofile.initTag()
            audiofile.tag.images.set(3, meta_data['artwork'], 'image/jpeg')
            audiofile.tag.title = meta_data['title']
            audiofile.tag.artist = meta_data['artists']
            audiofile.tag.album = meta_data['album']
            #genres = .artist(track_data['artists'][0]['id'])['genres']
            #gen = []
            #for genre in genres:
            #if self.genres.__contains__(genre.replace(' ', '-')):
            #gen.append(genre)
            #audiofile.tag.genre = ', '.join(gen)
            audiofile.tag.save()
        except Exception:
            print(chalk.red('error downloading a track'))
Example #10
0
def start_quiz(questions):
    score = 0
    for i in range(0, len(questions)):
        print('--------------------------------------------------------')
        print(f'Q{i+1}) {questions[i]["question"]}\n')
        sleep(0.3)

        for j in range(1, 5):
            print(f"({j}) {questions[i]['option'+str(j)]:30}", end='\t')
            sleep(0.2)
            if not j % 2: print()

        try:
            answer = int(input("\nEnter your option number: "))
            sleep(0.3)
            if not 0 < answer < 5:
                print(chalk.yellow("Please enter a choice between 1 and 4\n"))
                sleep(0.4)
                continue
        except ValueError:
            print(chalk.cyan('Invalid Choice\n'))
            sleep(0.4)
            continue

        print()
        if (questions[i]["correct_answer"] == "option" + str(answer)):
            print(chalk.green("Correct Answer!!!\n"))
            sleep(0.4)
            score = score + 1
        else:
            correct_answer = questions[i]["correct_answer"]
            print(
                chalk.red(
                    f"Wrong!! The Correct Answer is {questions[i][correct_answer]}"
                ))
            sleep(0.4)
            print()

        print('--------------------------------------------------------\n\n')

    print(chalk.yellow(f"Your Score is {score}/{len(questions)}"))
Example #11
0
def handle_amount(update, context):
    amount = update.message.text
    pattern = re.compile("^[1-9]\d*$")
    username = update.message.chat.username

    if amount == 'Back':
        amount = context.user_data['amount']
    if not pattern.match(amount):
        update.message.reply_text("Invalid input amount")
        return handle_transaction_menu(update, context)

    try:
        balance = checkRunningBalance(username)
    except Exception as e:
        update.message.reply_text(
            "Error: Cannot read current balance at the moment. Please try again later"
        )
        print(chalk.red("error in transaction handle_amount"))
        return handle_transaction_menu(update, context)

    if int(amount) > balance:
        update.message.reply_text(
            f"Insufficient funds, for transaction. You only have{balance}, please seek an admin for top up or make deposit to fund to your account"
        )
        return handle_transaction_menu(update, context)

    message = f"Amount to transfer: {amount} cents. Please specify item ID/Description"
    update.message.reply_text(message,
                              reply_markup=ReplyKeyboardMarkup(
                                  build_navigation_keyboard(),
                                  one_time_keyboard=True))

    # save to context
    context.user_data['amount'] = int(amount)

    # Next State
    return TRANSACTION_ITEM
Example #12
0
def handle_amount(update, context):
    amount = update.message.text
    action_type = context.user_data['fund_action']
    pattern = re.compile("^[1-9]\d*$")
    if amount == 'Back':
        amount = context.user_data['amount']
    if not pattern.match(amount):
        update.message.reply_text("Invalid input amount")
        return handle_fund_menu(update, context)

    try:
        balance = check_fund_balance()
    except Exception as e:
        update.message.reply_text(
            "Error: Cannot read current balance at the moment. Please try again later"
        )
        print(chalk.red("error in fund handle_amount"))
        return handle_fund_menu(update, context)
    if int(amount) > balance and action_type == 'withdraw':
        update.message.reply_text("Insufficient funds")
        return handle_fund_menu(update, context)

    if context.user_data['fund_action'] == 'withdraw':
        message = f"Amount to withdraw: {amount} cents. Please specify which admin account to deduct from"
    elif context.user_data['fund_action'] == 'deposit':
        message = f"Amount to deposit: {amount} cents. Please specify which admin account to deposit to"
    update.message.reply_text(message,
                              reply_markup=ReplyKeyboardMarkup(
                                  build_navigation_keyboard(),
                                  one_time_keyboard=True))

    # save to context
    context.user_data['amount'] = int(amount)

    # Next State
    return FUND_MANAGER
Example #13
0
    "/html/body/form/div[1]/table/tbody/tr[4]/td[2]/table/tbody/tr/td/table[2]/tbody/tr[6]/td[2]/input[1]"
)
course_title_chosen = driver.find_element_by_xpath(
    "/html/body/form/div[1]/table/tbody/tr[4]/td[2]/table/tbody/tr/td/table[2]/tbody/tr[5]/td[2]/span"
)
course_title = course_title_chosen.text
confirm_yes_button.click()

time.sleep(2)
#Checking the result of trying to enroll in the selected course
result_of_adding_course = driver.find_element_by_xpath(
    "/html/body/form/div[1]/table/tbody/tr[4]/td[2]/table/tbody/tr/td/table[2]/tbody/tr[1]/td[2]/span/font/b"
)

if result_of_adding_course.text == error_message:
    print(
        chalk.red("The course: " + course_title +
                  " could not be added for the following reason:"))
    reason_for_failure = driver.find_element_by_xpath(
        "/html/body/form/div[1]/table/tbody/tr[4]/td[2]/table/tbody/tr/td/table[2]/tbody/tr[2]/td[2]/span/font/b"
    )
    print(chalk.red(reason_for_failure.text))
    message_to_send = "The course: " + course_title + " could not be added for the following reason:" + reason_for_failure.text
    os.system(f'text-me.py "{message_to_send}"')
else:
    print(green(result_of_adding_course.text))
    message_to_send = success_message
    os.system(f'text-me.py "{message_to_send}"')

driver.quit()
    twilioNumber = input('Enter Twilio Phone number: ')
    myNumber = input('Enter your phone number: ')
    tickerSymbol = input('Enter Ticker Symbol to watch: ')
    writeInfo = (
        'Account Number: {}\nAccount Token: {}\nTwilio Number: {}\nMy Number: {}\nTicker Symbol: {}'
        .format(userID, authToken, twilioNumber, myNumber, tickerSymbol))
    infoFile.write(writeInfo)
    infoFile.close()

# Change stock to watch?
print('\nCurrently watching prices of {}...'.format(chalk.green(tickerSymbol)))
changeTicker()
# Choose if waiting to buy or sell
buyingOrSelling = buyOrSell()
# Set price to watch for
lowPrice = float(input(chalk.red('\nLow price to watch for?: ')))
highPrice = float(input(chalk.green('High price to watch for?: ')))

# Initialize Twilio Client
client = Client(userID, authToken)

# Initialize selenium settings
DRIVER_PATH = 'C:/webdrivers/chromedriver.exe'

options = Options()
options.headless = True
options.add_argument("--window-size=1920,1200")
options.add_argument("--log-level=3")  # Supress warning logs for visibility

# Start webpage
driver = webdriver.Chrome(options=options, executable_path=DRIVER_PATH)
Example #15
0
# Print an error message if the movement isn't allowed.
#
# If the user enters "q", quit the game.

if __name__ == "__main__":
    player = Player(room=room['outside'])

    start = True

    while start:
        # print(player)
        direction = input("\nā“  Which way do you want to go (n, s, e, w): ")

        try:
            print(navigator(direction, player))

            pick_up = input("ā“\tDo you want to pick up item (y/n): ")
            is_pickup(pick_up, player)
        except AttributeError:
            print(chalk.red("ERROR: "), "path not available")

        if direction == "q":
            print("GOOD GAME")
            break

        if player.room.name == "Treasure Chamber":
            print(
                chalk.green.bold(
                    "You found the treasure room but no treasure :("))
            break
def findHeightWordInSentences(lemmatizedSentences, plantName, category,
                              wikiLink):
    foundHeight = False
    with open('plantHeightData.csv', 'a', newline='') as csvfile:
        writer = csv.writer(csvfile)
        for sentence in lemmatizedSentences:
            for word in sentence:
                if (word == 'height' or word == 'tall'):
                    print(chalk.green.bold('height found for'), plantName)
                    foundHeight = True
                    sentenceThatContainHeightKeyword = " ".join(
                        str(x) for x in sentence)
                    # print(sentenceThatContainHeightKeyword,'\n')
                    # filterdSentence = tokenizer.tokenize(sentenceThatContainHeightKeyword)
                    # sentenceThatContainHeightKeyword = " ".join(str(x) for x in filterdSentence)
                    # print("plant Name is :" ,plantName, sentenceThatContainHeightKeyword);
                    doc = nlp(sentenceThatContainHeightKeyword)
                    count = 0
                    plant_height_data = []
                    for token in doc:
                        t = token.text
                        if t == 'm' or t == 'meter' or t == 'metre' or t == 'ft' or t == 'foot' or t == 'cm' or t == 'centimetre' or t == 'in':
                            # if len(doc) > (token.i+1):
                            # next_token = doc[token.i + 1]
                            prev_token = doc[token.i - 1]
                            if prev_token.like_num:
                                count += 1
                                # print("token",token," token.i",token.i," len(doc)",len(doc))
                                token_sentence = doc[prev_token.i:token.i + 1]
                                print("case#1",
                                      chalk.yellow.bold(token_sentence))
                                plant_height_data.append(token_sentence)
                                if doc[prev_token.i -
                                       2].like_num:  # 1 to 2 unit
                                    count += 1
                                    token_sentence = doc[prev_token.i -
                                                         2:token.i + 1]
                                    print("case#2",
                                          chalk.blue.bold(token_sentence))
                                    plant_height_data.append(token_sentence)
                                else:
                                    pass
                            else:  #get data for case#3 x-x unit
                                if prev_token.is_punct == False:
                                    token_sentence = doc[prev_token.i:token.i +
                                                         1]
                                    print("case#3",
                                          chalk.magenta(
                                              token_sentence))  #x-x uni
                                    plant_height_data.append(token_sentence)
                                else:
                                    pass  # do nothing if theres a punct mark

                                # if next_token.lower_ == "m" or next_token.lower_ == 'ft' or next_token.lower_ == 'meter' or next_token.lower_ == 'metre' or next_token.lower_ == 'cm' or next_token.lower_ == 'in' or next_token.lower_ == 'foot':
                                # count += 1
                                # token_sentence = doc[prev_token.i:next_token.i + 1]
                                # print('Height sentence',token_sentence)
                                # unit = token_sentence[len(token_sentence) - 1:len(token_sentence)]
                                # print(unit)
                                # writer.writerow([plantName,category,unit,'',token_sentence,'',wikiLink,sentenceThatContainHeightKeyword,''])

                    # unit cleanup
                    plant_height_data_str = []
                    plant_height_data_str_ft = ''
                    plant_height_data_str_cm = ''
                    plant_height_data_str_m = ''
                    plant_height_data_str_in = ''
                    for valueWithUnit in plant_height_data:
                        stringData = valueWithUnit.text
                        stringData = stringData.replace("-", " ")
                        stringData = stringData.replace("centimetre", "cm")
                        stringData = stringData.replace("foot", "ft")
                        stringData = stringData.replace("meter", "m")
                        stringData = stringData.replace("inch", "in")
                        stringData = stringData.replace('ā€“', ' ')
                        stringData = stringData.replace('to', ' ')
                        stringData = stringData.replace(',', '')
                        stringData = stringData.replace('1/2', '0.5')

                        if stringData.find('in') > 0:
                            plant_height_data_str_in = plant_height_data_str_in + stringData
                            plant_height_data_str_in = plant_height_data_str_in.replace(
                                'in', '')
                        if stringData.find('ft') > 0:
                            plant_height_data_str_ft = plant_height_data_str_ft + stringData
                            plant_height_data_str_ft = plant_height_data_str_ft.replace(
                                'ft', '')
                        if stringData.find(' m') > 0:
                            plant_height_data_str_m = plant_height_data_str_m + stringData
                            plant_height_data_str_m = plant_height_data_str_m.replace(
                                'm', '')
                        if stringData.find(' cm') > 0:
                            plant_height_data_str_cm = plant_height_data_str_cm + stringData
                            plant_height_data_str_cm = plant_height_data_str_cm.replace(
                                'cm', '')

                        plant_height_data_str.append(stringData)

                    print(chalk.red(plantName), plant_height_data)
                    print(chalk.green(plantName), plant_height_data_str)

                    # inch
                    # remove all characters
                    plant_height_data_str_in = removeAlphabets(
                        plant_height_data_str_in)
                    print(chalk.yellow(plantName), 'inch values',
                          plant_height_data_str_in)
                    plant_height_data_str_in = plant_height_data_str_in.split()
                    try:
                        plant_height_data_str_in = list(
                            map(float, plant_height_data_str_in))
                        plant_height_data_str_in = sorted(
                            plant_height_data_str_in)
                        print(chalk.cyan.bold(plantName), 'inch values',
                              plant_height_data_str_in)
                    except ValueError:
                        pass

                    # ft
                    plant_height_data_str_ft = removeAlphabets(
                        plant_height_data_str_ft)
                    print(chalk.yellow(plantName), 'ft values',
                          plant_height_data_str_ft)
                    plant_height_data_str_ft = plant_height_data_str_ft.split()
                    try:
                        plant_height_data_str_ft = list(
                            map(float, plant_height_data_str_ft))
                        plant_height_data_str_ft = sorted(
                            plant_height_data_str_ft)
                        print(chalk.cyan.bold(plantName), 'ft values',
                              plant_height_data_str_ft)
                    except ValueError:
                        pass
                    # m
                    plant_height_data_str_m = removeAlphabets(
                        plant_height_data_str_m)
                    print(chalk.yellow(plantName), 'm values',
                          plant_height_data_str_m)
                    plant_height_data_str_m = plant_height_data_str_m.split()
                    try:
                        plant_height_data_str_m = list(
                            map(float, plant_height_data_str_m))
                        plant_height_data_str_m = sorted(
                            plant_height_data_str_m)
                        print(chalk.cyan.bold(plantName), 'm values',
                              plant_height_data_str_m)
                    except ValueError:
                        pass

                    # cm
                    plant_height_data_str_cm = removeAlphabets(
                        plant_height_data_str_cm)
                    print(chalk.yellow(plantName), 'cm values',
                          plant_height_data_str_cm)
                    plant_height_data_str_cm = plant_height_data_str_cm.split()
                    try:
                        plant_height_data_str_cm = list(
                            map(float, plant_height_data_str_cm))
                        plant_height_data_str_cm = sorted(
                            plant_height_data_str_cm)
                        print(chalk.cyan.bold(plantName), 'cm values',
                              plant_height_data_str_cm)
                    except ValueError:
                        pass

                    if (len(plant_height_data_str_in) > 0):
                        temp = ['x'] * 10
                        for index, value in enumerate(
                                plant_height_data_str_in):
                            temp[index] = value

                        writer.writerow([
                            plantName, category, 'in', temp[0], temp[1],
                            temp[2], temp[3], temp[4], temp[5], temp[6],
                            temp[7], temp[8], temp[9], wikiLink,
                            sentenceThatContainHeightKeyword
                        ])

                    if (len(plant_height_data_str_cm) > 0):
                        temp = ['x'] * 10
                        for index, value in enumerate(
                                plant_height_data_str_cm):
                            temp[index] = value

                        writer.writerow([
                            plantName, category, 'cm', temp[0], temp[1],
                            temp[2], temp[3], temp[4], temp[5], temp[6],
                            temp[7], temp[8], temp[9], wikiLink,
                            sentenceThatContainHeightKeyword
                        ])

                    if (len(plant_height_data_str_ft) > 0):
                        temp = ['x'] * 10
                        for index, value in enumerate(
                                plant_height_data_str_ft):
                            temp[index] = value

                        writer.writerow([
                            plantName, category, 'ft', temp[0], temp[1],
                            temp[2], temp[3], temp[4], temp[5], temp[6],
                            temp[7], temp[8], temp[9], wikiLink,
                            sentenceThatContainHeightKeyword
                        ])

                    if (len(plant_height_data_str_m) > 0):
                        temp = ['x'] * 10
                        for index, value in enumerate(plant_height_data_str_m):
                            temp[index] = value

                        writer.writerow([
                            plantName, category, 'm', temp[0], temp[1],
                            temp[2], temp[3], temp[4], temp[5], temp[6],
                            temp[7], temp[8], temp[9], wikiLink,
                            sentenceThatContainHeightKeyword
                        ])

                    # if (count > 0):
                    # print(count,chalk.red.bold('tokens found in'),plantName,'\n')
                    # else:
                    # writer.writerow([plantName,category,'not found','','not found','',wikiLink,sentenceThatContainHeightKeyword,''])
                    # print(count,chalk.red('tokens matched in'),plantName,'\n')

    if (foundHeight == False):
        print(chalk.red("No Height for "), plantName)
        with open('plantHeightData.csv', 'a', newline='') as csvfile:
            writer = csv.writer(csvfile)
            writer.writerow([
                plantName, category, 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x',
                'x', 'x', 'x', wikiLink, 'x'
            ])
Example #17
0
def error(*args):
    args = map(js_value_to_string, args)
    print(chalk.red("[ERROR]"), *args, file=sys.stderr)
                    if problems:
                        plant_properties.append(problems.text)
                        Problems = problems.text
                    else:
                        Problems = ''

                    if garden_uses:
                        plant_properties.append(garden_uses.text)
                        GardenUses = garden_uses.text
                    else:
                        GardenUses = ''

            completePlantUrl = siteURL + planturl
            print(chalk.cyan(siteURL + planturl))
            print(chalk.red(completePlantUrl))
            with open('MBGCommonNames.csv', 'a') as writeFile:
                writer = csv.writer(writeFile)
                print(common_not_found)
                if (common_not_found == 0):
                    writer.writerow([
                        completePlantUrl, commonNameOriginal, CommonNameMBG,
                        botanicalName, botanicalNameMGB, Type, Family,
                        NativeRange, Zone, ZoneLow, ZoneHigh, Height,
                        HeightLow, HeightHigh, HeightUnit, Spread, SpreadLow,
                        SpreadHigh, SpreadUnit, BloomTime, BloomDescription,
                        Sun, Water, Maintenance, SuggestedUse, Flower,
                        Attracts, Fruit, Leaf, Other, Tolerate, Culture,
                        NoteworthyCharacteristics, Problems, GardenUses, ''
                    ])
Example #19
0
    for ele in attracts_elements:
      cleaned = ele.strip()
      # if cleaned in attractsUnique:
        # pass
      # else:
        # if cleaned != '':
          # attractsUnique.append(cleaned)
      
      if cleaned == 'Hummingbirds':
        Hummingbirds = 1
      elif cleaned == 'Butterflies':
        Butterflies = 1 
      elif cleaned == 'Birds':
        Birds = 1
      else:
        print(chalk.red('nothing found'),data[1])
    
    tolerate = data[30]
    tolerate_elements = tolerate.split(',')
    for ele in tolerate_elements:
      cleaned = ele.strip()
      # if cleaned in tolerateUnique:
      #   pass
      # else:
      #   if cleaned != '':
      #     tolerateUnique.append(cleaned)

      if cleaned == 'Erosion':
        Erosion = 1
      elif cleaned == 'Rabbit':
        Rabbit = 1