官术网_书友最值得收藏!

Organizing code in a .py file

Let's start with the snippet we worked with in Chapter 2Strings and Collections. Open a text editor – preferably one with syntax highlighting support for Python – and configure it to insert four spaces per indent level when you press the tab key. You should also check that your editor saves the file using the UTF 8 encoding as that's what the Python 3 runtime expects by default.

Create a directory called pyfund in your home directory. This is where we'll put the code for the chapter.

All Python source files use the .py extension, so let's get the snippet we wrote at the REPL at end of the previous module into a text file called pyfund/words.py. The file's contents should looks like this:

from urllib.request import urlopen

with urlopen('http://sixty-north.com/c/t.txt') as story:
story_words = []
for line in story:
line_words = line.decode('utf-8').split()
for word in line_words:
story_words.append(word)

You'll notice some minor differences between the code above and what we wrote previously at the REPL. Now that we're using a text file for our code we can pay a little more attention to readability, so, for example, we've put a blank line after the import statement.

Save this file before moving on.

主站蜘蛛池模板: 邯郸县| 恩平市| 凤阳县| 太仆寺旗| 怀柔区| 合肥市| 瑞安市| 沭阳县| 林口县| 九江县| 庆元县| 丰顺县| 德兴市| 林甸县| 庆安县| 遵义县| 康乐县| 玛沁县| 卫辉市| 沂源县| 镇原县| 海阳市| 米脂县| 白玉县| 阿拉善左旗| 荥阳市| 右玉县| 尚志市| 屯门区| 甘孜县| 漳平市| 游戏| 成都市| 赤峰市| 达孜县| 肇源县| 安阳市| 门源| 德安县| 思茅市| 丰都县|