python基础课程系列(十二)

10.3.6.分析文本
方法 split() 以空格为分隔符将字符串分拆成多个部分,并将这些部分都存储到一个列表中。结果是一个包含字符串中所有单词的列表,虽然有些单词可能包含标点。
-------------------------------------------------------
>>> title = "Alice in Wonderland"
>>> title.split()
['Alice', 'in', 'Wonderland']
-------------------------------------------------------
filename = 'Alice in Wonderland.txt'

try:
    with open(filename) as f:
        contents = f.read()
except FileNotFoundError:
    msg = 'Sorry, the file ' + filename + ' does not exit.'
    print(msg)
else:
    #计算文件大致包含多少个单词
    words = contents.split()
    num_words = len(words)
    print('The file ' + filename + ' has about ' + str(num_words) + ' words.')
-------------------------------------------------------
The file Alice in Wonderland.txt has about 30358 words.

10.3.7.使用多个文件
先建一个名为count_words()函数
-------------------------------------------------------
def count_words(filename):
    try:
        with open(filename) as f:
            contents = f.read()
    except FileNotFoundError:
        msg = 'Sorry, the file ' + filename + ' does not exist.'
        print(msg)
    else:
        words = contents.split()
        num_words = len(words)
        print('The file ' + filename + ' has about ' + str(num_words) + ' words.')
-------------------------------------------------------
>>> filename = 'Alice in Wonderland.txt'
>>> count_words(filename)
The file Alice in Wonderland.txt has about 30358 words.
-------------------------------------------------------
现在可以编写一个简单的循环,计算要分析的任何文本包含多少个单词了。为此,我们将要分析的文件的名称存储在一个列表中,然后对列表中的每个文件都调用 count_words() 。
>>> filenames = ['Alice in Wonderland.txt', ' Siddhartha.txt', 'Moby Dick.txt', 'Little Women.txt']
>>> for filename in filenames:
    count_words(filename)
    
The file Alice in Wonderland.txt has about 10869 words.
Sorry, the file  Siddhartha.txt does not exist.
The file Moby Dick.txt has about 5228 words.
The file Little Women.txt has about 4825 words.
-------------------------------------------------------
文件 siddhartha.txt 不存在,但这丝毫不影响这个程序处理其他文件.
在这个示例中,使用 try-except 代码块提供了两个重要的优点:避免让用户看到 traceback ;让程序能够继续分析能够找到的其他文件。如果不捕获因找不到 siddhartha.txt 而引发
的 FileNotFoundError 异常,用户将看到完整的 traceback ,而程序将在尝试分析 Siddhartha  后停止运行 —— 根本不分析 Moby Dick  和 Little Women

10.4.存储数据
模块 json 让你能够将简单的 Python 数据结构转储到文件中,并在程序再次运行时加载该文件中的数据。
10.4.1.使用 json.dump()  和 json.load()
我们来编写一个存储一组数字的简短程序,再编写一个将这些数字读取到内存中的程序。第一个程序将使用 json.dump() 来存储这组数字,而第二个程序将使用 json.load() 。
函数 json.dump() 接受两个实参:要存储的数据以及可用于存储数据的文件对象。
-------------------------------------------------------
>>> import json
>>> numbers = [2,3,5,7,11,13]
>>> filename = 'number.json'
>>> with open(filename, 'w') as f:
    json.dump(numbers, f)
-------------------------------------------------------
下面再编写一个程序,使用 json.load() 将这个列表读取到内存中
>>> import json
>>> filename = 'number.json'
>>> with open(filename) as f:
    numbers = json.load(f)
    
>>> print(numbers)
[2, 3, 5, 7, 11, 13]

10.4.2.保存和读取用户生成的数据
-------------------------------------------------------
import json

username = input('What is your name?')

filename = 'username.json'

with open(filename, 'w') as f:
    json.dump(username, f)
    print('We\'ll remember you when you come back, ' + username +'!')
-------------------------------------------------------
import json

filename = 'username.json'

with open(filename) as f:
    username = json.load(f)
    print('Welcome back, ' + username.title() + '!')

10.4.3.重构
你经常会遇到这样的情况:代码能够正确地运行,但可做进一步的改进 —— 将代码划分为一系列完成具体工作的函数。这样的过程被称为重构
-------------------------------------------------------
import json

def get_stored_username():
    """如果存储了用户名,就获取它"""
    filename = 'username.json'
    try:
        with open(filename) as f:
            username = json.load(f)
    except FileNotFoundError:
        return None
    else:
        return username

def get_new_username():
    """提示用户输入用户名"""
    username = input('What is your name?')
    filename = 'username.json'
    with open(filename, 'w') as f:
        json.dump(username, f)
    return username

def greet_user():
    """问候用户,并指出其名字"""
    username = get_stored_username()
    if username:
        print('Welcome back, ' + username + '!')
    else:
        username = get_new_username()
        print('We\'ll remember you when you come back, ' + username + '!')
-------------------------------------------------------
>>> greet_user()
What is your name?Eric
We'll remember you when you come back, Eric!
>>> greet_user()
Welcome back, Eric!
 

猜你喜欢

转载自blog.csdn.net/zhaocen_1230/article/details/81537102
今日推荐