学习python的第三天

用python实现词频统计时比较简单,但是需要区分是英文文本还是中文文本,两种不同的文本用到的方法稍微有点区别。

对英文文本进行统计:

def getText():
    txt = open("word.txt", "r").read()
    txt = txt.lower()
    for ch in '`~!"@$%^&*()_+-=|:";<>?,"./':
        txt = txt.replace(ch, " ")
    return txt


txt = getText()
words = txt.split()
counts = {}
for word in words:
    counts[word] = counts.get(word, 0) + 1
for word in counts:
    print(word + " " + str(counts.get(word)))

对中文文本进行统计:

import jieba

txt = open("word.txt", "r", encoding="utf-8").read()
words = jieba.lcut(txt)
counts = {}
for word in words:
    counts[word] = counts.get(word, 0) + 1
for word in counts:
    print(word + " " + str(counts[word]))

 文件操作:

(1)文件的打开:

rt = open("word.txt", "r")
'r'   只读模式,默认值,如果文件不存在,返回FileNotFoundError
'w'   覆盖写模式,文件不存在则创建,存在则完全覆盖
'x'   创建写模式,文件不存在则创建,存在则返回FileExistsError
'a'   追加写模式,文件不存在则创建,存在则在文件最后追加内容
'b'   二进制文件模式
't'   文本文件模式,默认值
'+'   与r/w/x/a一同使用,在原功能基础上增加同时读写功能

(2)文件的关闭:

rt.close()

 简易玫瑰花绘制:

import turtle as t

#定义一个曲线绘制函数
def DegreeCurve(n, r, d=1):
    for i in range(n):
        t.left(d)
        t.circle(r, abs(d))


#初始位置设定
s = 0.2 #size
t.setup(450*5*s, 750*5*s)
t.pencolor("black")
t.fillcolor("red")
t.speed(100)
t.penup()
t.goto(0, 900*s)
t.pendown()

#绘制花朵形状
t.begin_fill()
t.circle(200*s, 30)
DegreeCurve(60, 50*s)
t.circle(200*s, 30)
DegreeCurve(4, 100*s)
t.circle(200*s, 50)
DegreeCurve(50, 50*s)
t.circle(350*s, 65)
DegreeCurve(40, 70*s)
t.circle(150*s, 50)
DegreeCurve(20, 50*s, -1)
t.circle(400*s, 60)
DegreeCurve(18, 50*s)
t.fd(250*s)
t.right(150)
t.circle(-500*s, 12)
t.left(140)
t.circle(550*s, 110)
t.left(27)
t.circle(650*s, 100)
t.left(130)
t.circle(-300*s, 20)
t.right(123)
t.circle(220*s, 57)
t.end_fill()

#绘制花枝形状
t.left(120)
t.fd(280*s)
t.left(115)
t.circle(300*s, 33)
t.left(180)
t.circle(-300*s, 33)
DegreeCurve(70, 225*s, -1)
t.circle(350*s, 104)
t.left(90)
t.circle(200*s, 105)
t.circle(-500*s, 63)
t.penup()
t.goto(170*s, -30*s)
t.pendown()
t.left(160)
DegreeCurve(20, 2500*s)
DegreeCurve(220, 250*s, -1)

#绘制一个绿色叶子
t.fillcolor("green")
t.penup()
t.goto(670*s, -180*s)
t.pendown()
t.right(140)
t.begin_fill()
t.circle(300*s, 120)
t.left(60)
t.circle(300*s, 120)
t.end_fill()
t.penup()
t.goto(180*s, -550*s)
t.pendown()
t.right(85)
t.circle(600*s, 40)

#绘制另一个绿色叶子
t.penup()
t.goto(-150*s, -1000*s)
t.pendown()
t.begin_fill()
t.rt(120)
t.circle(300*s, 115)
t.left(75)
t.circle(300*s, 100)
t.end_fill()
t.penup()
t.goto(430*s, -1070*s)
t.pendown()
t.right(30)
t.circle(-600*s, 35)

t.done()
原文地址:https://www.cnblogs.com/SwiftAC/p/12255550.html