无法在两个python文件之间传递变量

时间:2017-09-19 19:20:15

标签: python variables

我有2个python文件。一个是speech.py​​,另一个是weather.py 我想要做的是,输入一个问题(即纽约天气如何),然后将城市名称传递给weather.py文件。哪个会找到该城市的天气并将结果返回到speech.py​​并且结果将由speech.py​​打印(这是我的主文件)。两个文件都给出错误,说明另一个文件没有分别名为forecast和city_to_find的属性。但我可以清楚地看到两个文件中的变量。

speech.py​​

from weather import forecast
    if i['tag'] == 'weather':
    sentence = 'How is weather in New York'
    print('Okay, Let me search for weather')
    city_ID = sentence.split()
    city_to_find = city_ID[-1]


 engine.say(forecast)

weather.py

import urllib.request
from bs4 import BeautifulSoup
import urllib.parse
from urllib.parse import  urljoin
from speech import city_to_find


city= city_to_find
weather_page = 'https://weather.com/en-IN/weather/today/l/'
NY ='USNY0996:1:US'


if city == 'New York':
    weather_page+=NY

    #print(weather_page)
    weather = urllib.request.urlopen(weather_page)
    weather_data = BeautifulSoup(weather, 'html.parser')

    temperature = weather_data.find('div', attrs={'class': 'today-daypart-temp'})
    temp = temperature.text.strip() # strip() is used to remove starting and trailing
    weather_condition = weather_data.find('span', attrs={'class': 'today-daypart-wxphrase'})
    update = weather_condition.text.strip() # strip() is used to remove starting and trailing

    forecast = 'Right now in '+city+' it is '+temp+' and '+update
    return forecast

我也尝试将整个文件互相导入(分别是导入天气和导入语音)。但没有运气。

任何人都可以帮我弄清楚我的错误吗?

注意:这两个程序分别正常工作

2 个答案:

答案 0 :(得分:1)

尝试

<强> weather.py

import urllib.request
from bs4 import BeautifulSoup
import urllib.parse
from urllib.parse import  urljoin

def forecast(city_to_find):
    city = city_to_find
    weather_page = 'https://weather.com/en-IN/weather/today/l/'
    NY ='USNY0996:1:US'

    if city == 'New York':
        weather_page+=NY

        #print(weather_page)
        weather = urllib.request.urlopen(weather_page)
        weather_data = BeautifulSoup(weather, 'html.parser')

        temperature = weather_data.find('div', attrs={'class': 'today-daypart-temp'})
        temp = temperature.text.strip() # strip() is used to remove starting and trailing
        weather_condition = weather_data.find('span', attrs={'class': 'today-daypart-wxphrase'})
        update = weather_condition.text.strip() # strip() is used to remove starting and trailing

        forecast = 'Right now in '+city+' it is '+temp+' and '+update
        return forecast

你可以调用函数

<强> speech.py​​

from weather import forecast
engine.say(forecast(city_to_find))

我修改了结构,我将城市发送到函数,不将这些数据从speech.py​​导入到weather.py中,函数在speech.py​​中返回进程的结果。

答案 1 :(得分:0)

在weather.py中定义一个函数,并从speech.py​​

调用它
forecast = weather.forecast(city_to_find)