0

これは私の 4 番目の python スクリプトです。初心者であることをご容赦ください。特定の日付の曜日を示すスクリプトを作成しています。1つのエラーを除いて、すべて正常に実行されます。何が間違っているかについてかすかな考えがありますが、あまり確信が持てません:

TypeError: 'int' オブジェクトは添字可能ではありません

#!/usr/bin/python
import sys, string

# Call example:  day_of_week(2,10,1988); February 10, 1988
def day_of_week(month, date, year):
    # January
    if month == 1: m = 11
    # February
    elif month == 2: m = 12
    # March
    elif month == 3: m = 1
    # April
    elif month == 4: m = 2
    # May
    elif month == 5: m = 3
    # June
    elif month == 6: m = 4
    # July
    elif month == 7: m = 5
    # August
    elif month == 8: m = 6
    # September
    elif month == 9: m = 7
    # October
    elif month == 10: m = 8
    # November
    elif month == 11: m = 9
    # December
    elif month == 12: m = 10

    # Calculate the day of the week
    dow = (date + ((13 * m-1)/5) + year[2:] + (year[2:]/4) + (year[:2]/4) - 2 * year[:2]) % 7)

    # Formatting!
    if dow == 0: return "Sunday"
    elif dow == 1: return "Monday"
    elif dow == 2: return "Tuesday"
    elif dow == 3: return "Wednesday"
    elif dow == 4: return "Thursday"
    elif dow == 5: return "Friday"
    elif dow == 6: return "Saturday"
    else: return "Error!"

try:
    m = int(raw_input("What month were you born in (1-12)?  "))
    if not 1 <= m <= 12: raise Exception("There are no months with a number higher than 12!")
    d = int(raw_input("On what date were you born on?  "))
    y = int(raw_input("What year were you born in?  "))
    print("\nYou were born on a %s!" % day_of_week(m,d,y))
except ValueError:
    print("You need to enter a number!")
4

3 に答える 3

3

この行で:

dow = (date + ((13 * m-1)/5) + year[2:] + (year[2:]/4) + (year[:2]/4) - 2 * year[:2]) % 7)

year(整数)を使用して、そこからスライスを返そうとしています。エラーが示すように、intオブジェクトではこれを行うことができません。目的を達成するには、文字列としてキャストする必要がありyearます。

ただし、より簡単な解決策は、モジュールの組み込み機能を使用しdatetimeて曜日を計算することです。

In [1]: import datetime

In [2]: my_date = datetime.date(2012, 11, 26)

In [3]: my_date.weekday()
Out[3]: 0

これは月曜日を開始日 (0) として使用します。現在のコードを維持するisoweekday()には、月曜日 = 1 のを使用できます。

In [11]: import datetime

In [12]: my_date = datetime.date(2012, 11, 26)

In [13]: my_date.isoweekday()
Out[13]: 1

次に、上記の @JonClement のスリック スニペットを使用して、その日の文字列を返すことができます。

In [14]: '{0:%A}'.format(my_date)
Out[14]: 'Monday'
于 2012-11-27T00:20:58.150 に答える
1

スライスするにはintstring最初にキャストする必要があります。str()

于 2012-11-27T00:21:26.137 に答える
1

int を文字列にキャストしないでください。算術を使用する:

century = year / 100
lasttwo = year % 100
dow = (date + ((13 * m-1)/5) + lasttwo + (lasttwo/4) + (century/4) - 2 * century) % 7)

そして、私は物理的にそのような挑戦に抵抗することができないので、残りのコードをもう少し Pythonic にしようとしました。

#!/usr/bin/python

"""Calculate the day of the week of dates"""


def day_of_week(month, day, year):
    """Return the name of the weekday of the given date

    >>> day_of_week(1, 1, 1970)
    'Friday'
    >>> day_of_week(11, 26, 2012)
    'Monday'
    """
    moff = (month + 9) % 12 + 1

    # Calculate the day of the week
    century = year / 100
    lasttwo = year % 100
    dow = (day + (13 * moff - 1) / 5 + lasttwo + lasttwo / 4 + century / 4
        - 2 * century) % 7

    # Formatting!
    return ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
        "Saturday")[dow]


def main():
    """Test the program, then run it interactively"""
    import doctest
    testresult = doctest.testmod()
    if testresult.failed:
        import sys
        sys.exit(1)
    try:
        month = int(raw_input("What month were you born in (1-12)?  "))
        if not 1 <= month <= 12:
            raise Exception("Month must be between 1 and 12!")
        day = int(raw_input("On what date were you born on?  "))
        year = int(raw_input("What year were you born in?  "))
        print("\nYou were born on a %s!" % day_of_week(month, day, year))
    except ValueError:
        print("You need to enter a number!")

if __name__ == '__main__':
    main()

実際のロジックはバージョンと同じであることに注意してください。少し単純なコードを使用しているだけです。あなたの最終目標は、実際にこの計算を実行することよりも、Python を学習することにあると思います。私が間違っている場合は、上記のすべてをスクラッチして、datetimeはるかに単純なモジュールを使用してください。

于 2012-11-27T00:28:28.977 に答える