Python для чайников, использующих данные bakeshare - PullRequest
0 голосов
/ 31 октября 2018

Я хочу запустить этот код, но у меня есть некоторые ошибки, и я не вижу проблемы. Код ниже. И нужно ли мне устанавливать глобальный список городов, месяца и дня?

import time
import pandas as pd
import numpy as np

CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv',
              'washington': 'washington.csv' }


def get_filters():
"""
Asks user to specify a city, month, and day to analyze.

Returns:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
"""
print('Hello! Let\'s explore some US bikeshare data!')

# get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs
cities = ('Chicago', 'New York', 'Washington')
while True:
city = input('Which of these cities do you want to explore : Chicago, New York or Washington? \n> ').lower()
if city in cities:
break

# get user input for month (all, january, february, ... , june)
months = ['january', 'february', 'march', 'april', 'may', 'june']
month = get_user_input('Now you have to enter a month to get some months result) \n> ', months)

# get user input for day of week (all, monday, tuesday, ... sunday)
days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday' ]
day = get_user_input('Now you have to enter a month to get some months result) \n> ', days)

print('-'*40)
return city, month, day

Ответы [ 2 ]

0 голосов
/ 01 ноября 2018

Использование .lower () - это нормально, но вы должны изменить свой список cities и свой запрос `CITY_DATA``, чтобы они соответствовали именам (так, Нью-Йорк -: Нью-Йорк).

CITY_DATA = { 'chicago': 'chicago.csv', 'new york': 'new_york_city.csv',
          'washington': 'washington.csv' }


def get_filters():
    """
    Asks user to specify a city, month, and day to analyze.

    Returns:
    (str) city - name of the city to analyze
    (str) month - name of the month to filter by, or "all" to apply no month filter
    (str) day - name of the day of week to filter by, or "all" to apply no day filter
    """
    print('Hello! Let\'s explore some US bikeshare data!')

    # get user input for city (chicago, new york city, washington). HINT: Use a while  loop to handle invalid inputs
    cities = ('chicago', 'new york', 'washington')
    while True:
        city = raw_input('Which of these cities do you want to explore : Chicago, New York or Washington? \n> ').lower()

        if city in cities:
            break

    # get user input for month (all, january, february, ... , june)
    months = ['january', 'february', 'march', 'april', 'may', 'june']
    month = raw_input('Now you have to enter a month to get some months result \n> {} \n>'.format(months)).lower()

    # get user input for day of week (all, monday, tuesday, ... sunday)
    days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']
    day = raw_input('Now you have to enter a day to get some days result \n> {} \n>'.format(days)).lower()

    print('-'*40)

    if month == '' and day == '':
        return city, months, days
    elif month == '' and day != '':
        return city, months, day
    elif month != '' and day == '':
        return city, month, days
    else:
        return city, month, day


city, month, day = get_filters()

print(city, month, day) 

Если вы используете Python 2.7, вы должны использовать raw_input() вместо input().

0 голосов
/ 31 октября 2018

Если я вас правильно понял, я думаю, что это то, что вы должны сделать:

CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv',
          'washington': 'washington.csv' }


def get_filters():
    """
    Asks user to specify a city, month, and day to analyze.

    Returns:
    (str) city - name of the city to analyze
    (str) month - name of the month to filter by, or "all" to apply no month filter
    (str) day - name of the day of week to filter by, or "all" to apply no day filter
    """
    print('Hello! Let\'s explore some US bikeshare data!')

    # get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs
    cities = ('Chicago', 'New York', 'Washington')
    while True:
        city = input('Which of these cities do you want to explore : Chicago, New York or Washington? \n> ').capitalize() #was lower()
        if city in cities:
            break

    # get user input for month (all, january, february, ... , june)
    months = ['january', 'february', 'march', 'april', 'may', 'june']
    month = input('Now you have to enter a month to get some months result \n> {} \n> '.format(months))

    # get user input for day of week (all, monday, tuesday, ... sunday)
    days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']
    day = input('Now you have to enter a dau to get some days result \n> {} \n> '.format(days))

    print('-'*40)

    if month == '' and day == '':
        return city, months, days
    elif month == '' and day != '':
        return city, months, day
    elif month != '' and day == '':
        return city, month, days
    else:
        return city, month, day


city, month, day = get_filters()

print(city, month, day)

Несколько вещей на заметку: Ввод города был установлен на «.lower ()», в то время как список городов содержал заглавные буквы. Поэтому я изменил его на capitilize ().

Также вы хотели, чтобы он возвращался каждый день и месяц, если пользователь не указал какие-либо данные. Поэтому в конце я добавил простой if-тест, чтобы проверить это. Кроме того, я использовал '-format ()', чтобы отобразить различные параметры, которые пользователь имеет для ввода. Надеюсь, все ясно!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...