分析文本
title = “Alice in Wordlad”
title.split()
filename = ‘alice.txt’
try:
with open(filename) as f_obj:
contens = f_obj.read()
except FileNotFoundError:
msg = “Sorry,the file " + filename + " does not it!”
print(msg)
else:
words = contens.split()
num_words = len(words)
print("the file " + str(num_words))
使用多个文件
def count_words(filename_1):
“”“计算一个文件包含多少单词”""
try:
with open(filename_1) as f_obj:
conten = f_obj.read()
except FileNotFoundError:
msg_1 = “Sorry,the file " + filename_1 + " does not it!”
print(msg_1)
else:
word = conten.split()
num_word = len(word)
print(“the file " + str(num_word) + " words.”)
filename_1 = ‘alice.txt’
count_words(filename_1)
filename_1s = [‘alice.txt’, ‘fru.txt’]
for filename_1 in filename_1s:
count_words(filename_1)
存储数据
import json
numbers = [1, 2, 3, 4, 5, 6]
nu_name = ‘numbers.json’
with open(nu_name, ‘w’) as nu_obj:
json.dump(numbers, nu_obj)
读取数据
n_name = ‘numbers.json’
with open(n_name, ‘r’, ) as n_obj:
nu = json.load(n_obj)
print(nu)