1. 程式人生 > >2017-5-17 分析文本

2017-5-17 分析文本

exc int {} ont 異常 拋出異常 otf 字符串轉換 bre

異常處理文本:
filename = ‘alice.txt‘
try:
with open(filename,encoding=‘utf-8‘) as f:

contents = f.read()
except FileNotFoundError:
msg = ‘文件不存在...‘

else:
words = contents.split()
num_words = len(words)
print(‘the file‘ + filename + ‘ has about ‘ + str(num_words)) 如果文件不存在,拋出異常,如果存在,打印出有多少個元素,,默認空格分割


函數式:
filename = ‘alice.txt‘

def number_worlds():
try:
with open(filename,encoding=‘utf-8‘) as f:
contents = f.read()
except FileNotFoundError:
print("the file dose not exits")

else:
content_worlds = contents.split()
words = len(content_worlds)

print("the file has " + str(words) + " words" )

number_worlds()

for 循環 處理多個文本:


def number_worlds():
try:
with open(filename,encoding=‘utf-8‘) as f:
contents = f.read()
except FileNotFoundError:
print("the file dose not exits")

else:
content_worlds = contents.split()
words = len(content_worlds)

print("the file has " + str(words) + " words" )

filenames = [‘a.txt‘,‘b.txt‘,‘alice.txt‘]
for filename in filenames:
number_worlds()




def number_worlds():
try:
with open(filename,encoding=‘utf-8‘) as f:
contents = f.read()
except FileNotFoundError:
pass

else:
content_worlds = contents.split()
words = len(content_worlds)

print("the file has " + str(words) + " words" )

filenames = [‘a.txt‘,‘b.txt‘,‘alice.txt‘]
for filename in filenames:
number_worlds()



line = "Row,row,row your boat"
print(line.count(‘row‘))
print(line.lower().count(‘row‘)) count 統計相同的單詞出現多少次,lower,將字符串轉換為小寫




json dump存儲數據:
import json
number = [2,3,4,5,6,7,8,9]

filename = ‘alice.txt‘

with open(filename,‘a‘,encoding=‘utf-8‘) as f:
json.dump(number,f)


import json

username = str(input("what is your name:"))
password = str(input("please input your psswd:"))

SQL = {}
SQL[username] = password

with open(‘alice.txt‘,‘a‘,encoding=‘utf-8‘) as f:
json.dump(SQL,f)


json load讀取數據:
import json
filename = ‘alice.txt‘
with open(filename,encoding=‘utf-8‘) as f:
numbers = json.load(f)
print(numbers)




import json
def get_str():
filename = ‘alice.txt‘
try:
with open(filename,encoding=‘utf-8‘) as f:
str_load = json.load(f)
print(str_load)


except FileNotFoundError:
name = input("what your name:")
passwd = input("please inout your passwd:")

dicts = {}
dicts[name] = passwd
with open(filename,‘w‘,encoding=‘utf-8‘) as f:
json.dump(dicts,f)

get_str()




from open_file import get_formatted_name

print("Enter ‘q‘ at any time to quit")

while True:
first = input("\nPlease give me a first name:")
if first == ‘q‘:
break
last = input("Please give me a last name:")
if last == ‘q‘:
break

formatted_name = get_formatted_name(first,last)
print("\tNealty formatted name: " + formatted_name + ‘.‘)

單元測試::
import unittest
from open_file import get_formatted_name

class NameTestCase(unittest.TestCase):

def test_first_name(self):
formatted_name = get_formatted_name(‘zn‘,‘zyy‘)

self.assertEqual(formatted_name,‘Zn Zyy‘)
unittest.main()











2017-5-17 分析文本