io_input.py
# 用户输入输出
# 通过切片将序列里的内容转置的tip
def reverse(text):
return text[::-1]
# 判断是不是回文
def is_palindrome(text):
text = preprocess(text)
return text == reverse(text)
# 忽略文本的空格、标点和大小写
def preprocess(text):
# 都变成小写
text = text.lower()
# 删掉空格
# strip() " xyz " --> "xyz"
# lstrip() " xyz " --> "xyz "
# rstrip() " xyz " --> " xyz"
# replace(' ','') " x y z " --> "xyz"
text = text.replace(' ','')
# 删掉英文标点符号
# 需要导入string里的punctuation属性
import string
for char in string.punctuation:
# 为什么这里一定要用自身去替换
# text1 = text.replace(char,'')
text = text.replace(char,'')
return text
something = input("Enter text: ")
if is_palindrome(something):
print('Yes, it is a palindrome.')
else:
print('No, it is not a palindrome')
io_using_file.py
# 文件读写
poem = '''\
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
'''
# 'r'阅读 'w'写入 'a'追加
# 't' 文本模式 'b'二进制模式
# 打开文件以编辑('w')
f = open('poem.txt','w')
# 向文件中编写文本
f.write(poem)
# 关闭文件
f.close()
# 如果没有特别指定,将假定启用默认的'r'模式
f = open('poem.txt')
while True:
# readline() 读取文件的每一行还包括了行末尾的换行符
line = f.readline()
# 长度为零指示 EOF
# 当返回一个空字符串时,表示我们已经到了文件末尾要退出循环
if len(line) == 0:
break
# 每行line的末尾都有换行符因为他们是从一个文件中进行读取的
print(line,end='')
# 关闭文件
f.close()
io_pickle.py
# Python中提供了一个Pickle Module
# 它可以将Python对象存储到一个文件中 这样可以 持久地Persistently存储对象
# dump 与 load
import pickle
# 存储对象的文件名
shoplistfile = 'shoplist.data'
# list里的东西
shoplist = ['apple','mango','carrot']
# 写到文件里
f = open(shoplistfile,'wb') #以二进制模式写入
# Dump the object to a file (Pickling)
pickle.dump(shoplist,f)
f.close()
# 销毁shoplist变量
del shoplist
# 从文件再次读入
f = open(shoplistfile,'rb')
# Load the object from the file (Unpickling)
storedlist = pickle.load(f)
print(storedlist)
io_unicode.py
import io
f = io.open('abc.txt','wt',encoding='utf-8')
f.write(u'我是一个中国人')
f.close()
text = io.open('abc.txt',encoding='utf-8').read()
print(text)
网友评论