首页 > 代码库 > 2017-5-17 分析文本
2017-5-17 分析文本
异常处理文本:
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 分析文本
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。