2017年2月6日21:02:08

从昨天的问题当中走出来,顿时觉得轻松了许多。回过头来看,昨天下午的那阵焦灼确实由急躁所引起,越急越慌,好在昨晚整理下思路之后今天解决掉。现在将继续改写代码,在这之前我想先去了解if __name__ == '__main__':语句的意义。

_name_

stackoverflow果然是妙站,一篇问答直接搞定:

When the Python interpreter reads a source file, it executes all of the code found in it.

Before executing the code, it will define a few special variables. For example, if the python interpreter is running that module (the source file) as the main program, it sets the special name variable to have a value "main". If this file is being imported from another module, name will be set to the module's name.

所以我便知道如何更好的组织之前的程序了。至于为什么自己想到要了解if __name__ == '__main__':语句的意义,那是因为昨天下午参考 @shippomiru 代码时发现她如此做,一时好奇。

什么是JSON?

通过API获取到的结果是这样的:

{"results":[{"location":{"id":"WX4FBXXFKE4F","name":"北京","country":"CN","path":"北京,北京,中国","timezone":"Asia/Shanghai", "timezone_offset":"+08:00"},"now":{"text":"多云","code":"4","temperature":"1"},"last_update":"2017-02-06T20:50:00+08:00"}]}

卡包里面提到JSON格式,应该这种内容就是它了。不管怎样,先阅读下卡包上面的参考链接(Introducing JSON, JSON encoder and decoder, JSON Response Content)。

JSON是一种抽象于编程语言之上的数据交换格式,这种格式对于计算机来说非常容易解析,且便于开发者阅读。它有两种基础结构:Object与Array,前者由多个“name/value”组成(无序集合),后者有多个“value”组成(有序),下面是这两兄弟更详尽的解释:

An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).

An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).

对于里面的value元素,它可以表示的东西有很多:

A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.

A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string. A string is very much like a C or Java string.

解析结果

从第一篇参考文章当中了解了JSON的表示方法,但在后面文章中依然不知道如何使用,之后搜索到一篇中文文章,觉得很不错。然而通过写作下面的代码尝试去解析返回的结果却不对:

parsed_result = json.loads(result)
print parsed_result['text']

提示如下错误:

> python Code3_1_WeatherQuery_CLI.py

Traceback (most recent call last):
  File "Code3_1_WeatherQuery_CLI.py", line 52, in <module>
    print parsed_result['text']
KeyError: 'text'

调测了一半天才发现是自己对字典数据结构的理解不充分。之后一步一步添加打印,再修改,总算通过。

results matching ""

    No results matching ""