質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Q&A

解決済

1回答

2470閲覧

requestをimportして動作するプログラムが動かない(仮想環境下)

goliragolira

総合スコア26

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

0グッド

0クリップ

投稿2018/03/09 06:38

編集2018/03/09 07:57

初めましてpython初心者のgoliraです。
今、pythonの仮想環境vent上でrequestを下記プログラムで動かそうとしたのですが
プログラム自体は立ち上がるのですが、"天気"と打っても反応が無く、他のif文である
"干支"、"選ぶ"等のキーワードにも何故か反応しなくなりました。
どうすれば正常に動作するのか、ご教授お願いします。

1:プログラムコード

from import_eto import eto_command
from my_random import choice_command, dice_command
from import_hiduke import(kyou_command, ima_command,
youbi_command)
from forecast import weather_command

def len_command(command):
_ cmd, text = command.split()
_ length = len(text)
_ response = "文字列の長さは{}です".format(length)
_ return response

def heisei_command(command):
_ heisei, year_str = command.split()
_ if year_str.isdigit():
_ year = int(year_str)

_ if year >= 1989:
_ heisei_year = year - 1988
_ response = "西暦{}年は、平成{}年です".format(year, heisei_year)
_ else:
_ response = "西暦{}年は、平成ではありません".format(year)

_ else:
_ response = "数値を指定して下さい"
_ return response

aisatu_file = open("aisatu.txt", encoding="utf-8")
raw_data = aisatu_file.read()
aisatu_file.close
lines = raw_data.splitlines()

bot_dict = {}
for line in lines:
_ word_list = line.split(",")
_ key = word_list[0]
_ response = word_list[1]
_ bot_dict[key] = response

while True:
_ command = input("なんか言え ")
_ response = ""
_ try:
_ for key in bot_dict:
_ if key in command:
_ response = bot_dict[key]
_ break

_ if "平成" in command:
_ response = heisei_command(command)

_ if "長さ" in command:
_ response = len_command(command)

_ if "干支" in command:
_ response = eto_command(command)

_ if "選ぶ" in command:
_ response = choice_command(command)

_ if "サイコロ" in command:
_ response = dice_command(command)

_ if "今日" in command:
_ response = kyou_command()

_ if "現在" in command:
_ response = ima_command()

_ if "曜日" in command:
_ response = youbi_command(command)

_ if "天気" in command:
_ response = weather_command()
_ if not response:
_ response = "日本語喋れや豚野郎"

_ print(response)

_ if "さようなら" in command:
_ print("二度と開くなよまじで")
_ break

except Exception as e: print("予期せぬエラーが発生しました") print("種類:", type(e)) print("内容:", e)

”import_eto.py”のコード

#coding:utf-8

def eto_command(command):
_ eto, year = command.split()
_ eto_list = ("子", "丑", "寅", "卯", "辰", "巳", "午",
_ "未", "申", "酉", "戌", "亥")
_ eto_number = (int(year) + 8) % 12
_ eto_name = eto_list[eto_number]

_ response = "{}年生まれの干支は「{}」です".format(year, eto_name)
_ return response

"my_random.py"のコード

import random

def choice_command(command):
_ data = command.split()
_ choiced = random.choice(data[1:])
_ response = "「{}」が選ばれました".format(choiced)
_ return response

def dice_command(command):
_ num = random.randrange(1, 100)
_ response = "「{}」の目が出ました".format(num)
_ return response

"import_hiduke.py"のコード

rom datetime import date, datetime

def kyou_command():
_ today = date.today()
_ response = "今日の日付は{}です".format(today)
_ return response

def ima_command():
_ now = datetime.now()
_ response = "現在日時は{}です".format(now)
_ return response

def youbi_command(command):
_ try:
_ data = command.split()
_ year = int(data[1])
_ month = int(data[2])
_ day = int(data[3])
_ one_day = date(year, month, day)

_ weekday_str = "月火水木金土日"
_ weekday = weekday_str[one_day.weekday()]

_ response = "{}は、{}曜日です".format(one_day, weekday)

_ except IndexError:
_ response = "3つの値(年月日)を空白で区切って入力して下さい"
_ except ValueError:
_ response = "正しい日付を入力して下さい"

_ return response

"forecast.py"のコード

import requests

def weather_command():
_ base_url = "http://weather.livedoor.com/forecast/webservice/json/v1"
_ city_code = "230010"
_ url = "{}?city={}".format(base_url, city_code)
_ r = requests.get(url)
_ weather_data = r.json()
_ city = weather_data["location"]["city"]
_ label = weather_data["forecasts"][0]["dateLabel"]
_ telop = weather_data["forecasts"][0]["telop"]

_ response = "{}の{}の天気は「{}」です".format(city, label, telop)
_ return response

2:エラーコード

なんか言え 干支
予期せぬエラーが発生しました
種類: <class 'ValueError'>
内容: not enough values to unpack (expected 2, got 1)
なんか言え 選ぶ
予期せぬエラーが発生しました
種類: <class 'IndexError'>
内容: Cannot choose from an empty sequence
なんか言え 天気
なんか言え 天気
なんか言え 天気

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

LouiS0616

2018/03/09 06:44

あと、手元で実行できるようにimport_eto.pyなども可能なら下さいな。
goliragolira

2018/03/09 07:17

いつも迅速な回答、ありがとうございます。直ぐに対処してみます。
yoorwm

2018/03/09 07:24

「初めまして」なのに「いつも迅速な回答」なのですか?
goliragolira

2018/03/09 07:27

初めて見て頂く人も居るかと、思いまして、すいません、、、
退会済みユーザー

退会済みユーザー

2018/03/09 08:02

コードブロックの前後を```で囲んでください。もしくは、コード部分をマウスで選択して上側のタブ</>でも同じことができます。
guest

回答1

0

ベストアンサー

とりあえずエラーの原因だけ指摘します。

なんか言え 干支

予期せぬエラーが発生しました
種類: <class 'ValueError'>
内容: not enough values to unpack (expected 2, got 1)

import_eto.eto_command を見る限り、西暦も併せて入力すべきです。

なんか言え 選ぶ

予期せぬエラーが発生しました
種類: <class 'IndexError'>
内容: Cannot choose from an empty sequence

やはり my_random.choice_command を見る限り、選択肢を渡すべきです。


基本的には書いたとおりにしか動いていないので、関数の呼び出し方にご留意ください。
また、例外の安易な握り潰しは絶対にしないようにしてください。

Wandboxにコードを起こして再現させたので、一応共有しておきます。Wandbox

コードブロックの適用の仕方

次のようにコードブロックを利用出来ます。

Python

1def main(): 2 print('Hello World!') 3 4if __name__ == __main__: 5 main()

方法は二つあります。
0. コードをハイライトした状態で<code>ボタンを押す
0. マークダウンを手動で入力する Qiita - Markdown記法 チートシート - コードの挿入

書いてみた

部分的ですが、参考までに。

main.py

Python

1from command import eto_command, choice_command 2 3command_dict = { 4 '干支': eto_command, 5 '選ぶ': choice_command, 6} 7 8def interpret_command(input_str): 9 command, *args = input_str.split() 10 11 if command in command_dict: 12 return command_dict[command](*args) 13 14 return f'「{command}」の意味がわかりません。' 15 16 17def main(): 18 while True: 19 input_str = input('なんか入力してね: ') 20 if not input_str: 21 continue 22 23 if 'さようなら' == input_str: 24 print('了解。システムを終了します。') 25 break 26 27 print( 28 interpret_command(input_str), end='\n\n' 29 ) 30 31 32if __name__ == '__main__': 33 main()

command.py

Python

1import random 2 3 4def eto_command(*year_strs): 5 if len(year_strs) != 1: 6 return 'コマンドと一緒に西暦を一つだけ入力してね。' 7 8 year_str = year_strs[0] 9 try: 10 year = int(year_str) 11 except ValueError: 12 return f'{year_str}は西暦だと解釈できないよ。' 13 14 eto = [ 15 "子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥" 16 ][(year + 8) % 12] 17 18 return f'{year}年生まれの干支は「{eto}」です。' 19 20 21def choice_command(*candidate_list): 22 if not candidate_list: 23 return 'そもそも選択肢がないよ。' 24 25 choiced = random.choice(candidate_list) 26 return f'「{choiced}」が選ばれました。'

実行例 おまけ:Wandbox

plain

1なんか入力してね: 干支 2コマンドと一緒に西暦を一つだけ入力してね。 3 4なんか入力してね: 干支 2018 52018年生まれの干支は「戌」です。 6 7なんか入力してね: 干支 2018 2019 8コマンドと一緒に西暦を一つだけ入力してね。 9 10なんか入力してね: 干支 3.14 113.14は西暦だと解釈できないよ。 12 13なんか入力してね: 選ぶ 14そもそも選択肢がないよ。 15 16なんか入力してね: 選ぶ 1 2 3 17「1」が選ばれました。 18 19なんか入力してね: 選ぶ 1 2 3 20「1」が選ばれました。 21 22なんか入力してね: 選ぶ 1 2 3 23「2」が選ばれました。 24 25なんか入力してね: 面白いこと言って 26「面白いこと言って」の意味がわかりません。 27 28なんか入力してね: 29なんか入力してね: さようなら 30了解。システムを終了します。

投稿2018/03/09 08:14

編集2018/03/09 09:06
LouiS0616

総合スコア35660

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

goliragolira

2018/03/09 11:01

ありがとうございます! 試してみます!
goliragolira

2018/03/09 11:14

動きました! 本当にありがとうごさいます!
LouiS0616

2018/03/09 12:35

解決されたようで何よりです。 今回のコードが失敗した原因は主に次の二つですね。 1. 関数の正しい用法を把握できていなかったこと。 2. エラーを適切にハンドリング出来ず、情報が潰れてしまっていたこと。 例外を安易に使うと一気にデバッグが難しくなります。 tryは、ここぞという場面以外では使わない方が良いでしょう。もちろん、その『ここぞ』を判断するためには幾度とない失敗が必要ではあるのですが。 ただし except Exception はほぼ全ての例外を捕捉してしまうので厳禁です。 --- コードブロックの適用も出来るようにしておいてくださいね。
goliragolira

2018/03/23 10:54

エラーの把握をするためにも、try、exceptの使い方には気を付けたいと思います。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問