字符串操作练习:星座、凯撒密码、99乘法表、词频统计预处理

1、实例:输出12个星座符号,以反斜线分隔。

for i in range(12):
    print(chr(9800+i),end="/")

输出结果:

♈/♉/♊/♋/♌/♍/♎/♏/♐/♑/♒/♓/

2、实例:恺撒密码的编码

1 plaincode = input("请输入明文:")
2 for p in plaincode:
3     if ord("a") <= ord(p) <= ord("z"):
4         print(chr(ord("a") +  (ord(p) - ord("a") + 3) % 26),end = "")
5     else:
6         print(p , end = "")

输出结果:

请输入明文:python is a good language
sbwkrq lv d jrrg odqjxdjh

3、输入姓名,格式输出:占4位、居中、不足4字的以空格填充。

1 name = input("请输入你的名字:")
2 print("{: ^4}".format(name))

输出结果:

请输入你的名字:嘻嘻
 嘻嘻 

4、格式化输出:中华人民共和国国内生产总值(GDP)689,136.89亿元(2015年)(千分位、2位小数,浮点数)

1 gdp = 689136.89
2 print("中华人民共和国国内生产总值(GDP){:,.2f}亿元(2015年)".format(gdp))

输出结果:

中华人民共和国国内生产总值(GDP)689,136.89亿元(2015年)

5、实例:打出99乘法表

1 for i in range(1,10):
2     for j in range(1,i+1):
3         print("{}x{}={:<2}".format(i,j,i*j),end=" ")
4     print("\n")

输出结果:

1x1=1  

2x1=2  2x2=4  

3x1=3  3x2=6  3x3=9  

4x1=4  4x2=8  4x3=12 4x4=16 

5x1=5  5x2=10 5x3=15 5x4=20 5x5=25 

6x1=6  6x2=12 6x3=18 6x4=24 6x5=30 6x6=36 

7x1=7  7x2=14 7x3=21 7x4=28 7x5=35 7x6=42 7x7=49 

8x1=8  8x2=16 8x3=24 8x4=32 8x5=40 8x6=48 8x7=56 8x8=64 

9x1=9  9x2=18 9x3=27 9x4=36 9x5=45 9x6=54 9x7=63 9x8=72 9x9=81 

6、实例: 下载一首英文的歌词或文章,统计单词出现的次数,将所有,.?!替换为空格,将所有大写转换为小写。

  我从网上下载哈姆雷特英文版,进行的统计

def getText(book):
    txt = open(book,"r",encoding='utf-8').read()
    txt = txt.lower()
    for ch in '!#"$&()*+,-./:;<+.>?@[\\]^_`{|}~':
        txt = txt.replace(ch," ")
    return txt

book = "hamlet.txt"
hamletTxt = getText(book)

words = hamletTxt.split()
counts = {}
for word in words:
    counts[word] = counts.get(word,0)+1
items = list(counts.items())
items.sort(key = lambda x:x[1], reverse = True)
for i in range(10):
    word , count = items[i]
    print ("{:<10}{:>5}".format(word,count))

输出结果:

the        1137
and         965
to          754
of          667
you         550
a           542
i           541
my          514
hamlet      462
in          436

7、用webbrowser,uweb.open_new_tab('url')打开校园新闻列表

1 import webbrowser as web
2 web.open_new_tab("http://news.gzcc.cn/html/xiaoyuanxinwen/")

 

posted @ 2017-09-18 16:40  谢牧谚  阅读(382)  评论(0编辑  收藏  举报