Python笔记七:经典例题大田字格,七段数码管绘制,三国演义词频统计及文本朗读

利用python来进行大田字格,三国演义词频统计及文本朗读等简单程序的编写,适合新手小白尝试,本人也是新手小白一个,代码经过本人运行测试通过。

一、大田字格

def draw(n):
    l = 4    #5为每个小方格的边长
    line=(l+1)*n+1
    for i in range(line):
        if i%(l+1) == 0:
            print(n*("+"+"- "*l),end="")
            print("+")
        else:
            print(n*("|"+"  "*l),end="")
            print("|")
n=eval(input("请输入方块数:"))
draw(n)

Python笔记七:经典例题大田字格,七段数码管绘制,三国演义词频统计及文本朗读_第1张图片

输入的值为横向和竖向的小方格个数

 二、七段数码管绘制

from turtle import *
import datetime
import turtle
def drawline(isdraw):#画单段线,isdraw为真画线,否则不画
    pendown() if isdraw else penup()   
    pensize(5)
    forward(40)
    right(90)

def drawnum(n):#画数字n 
    drawline(True) if n in [2,3,4,5,6,8,9] else drawline(False)
    drawline(True) if n in [0,1,3,4,5,6,7,8,9] else drawline(False)
    drawline(True) if n in [0,2,3,5,6,8,9] else drawline(False)
    drawline(True) if n in [0,2,6,8] else drawline(False)
    left(90)
    drawline(True) if n in [0,4,5,6,8,9] else drawline(False)
    drawline(True) if n in [0,2,3,5,6,7,8,9] else drawline(False)
    drawline(True) if n in [0,1,2,3,4,7,8,9] else drawline(False)
    left(180)
    penup()
    forward(20)
setup(800,350,200,200)
penup()
forward(-300)
def drawdate(date):
    pencolor("red")
    for i in date:
        if i =='-':
            write('年',font=("Arial",18,"normal"))
            pencolor("green")
            fd(40)
        elif i =='=':
            write('月',font=("Arial",18,"normal"))
            pencolor("blue")
            fd(40)
        elif i =='+':
            write('日',font=("Arial",18,"normal"))
        else:
            drawnum(eval(i))
drawdate(datetime.datetime.now().strftime('%Y-%m=%d+'))
hideturtle()
done()

Python笔记七:经典例题大田字格,七段数码管绘制,三国演义词频统计及文本朗读_第2张图片

 三、三国演义词频统计

import jieba
txt = open("三国演义.txt","r",encoding='utf-8').read()
words = jieba.lcut(txt)
counts = {}
for w in words:
    if len(w) == 1:
        continue
    else:
        counts[w] = counts.get(w,0)+1
items = list(counts.items())
items.sort(key =lambda x:x[1],reverse=True)
fo = open("三国演义_统计.txt","w+")
for i in range(200):
    fo.writelines("{:<10}   {:>5}\n".format(items[i][0],items[i][1]))
fo.close()

Python笔记七:经典例题大田字格,七段数码管绘制,三国演义词频统计及文本朗读_第3张图片

 四、文本朗读

以三国演义文本为例,引用pyttsx3库即可完成文本的朗读

安装pyttsx3库

我使用的是pip3.9,其目录为F:\Program Files (x86)\Microsoft Visual Studio\Shared\Python39_64\Scripts,在DOS命令下,先转入安装目录下执行pip,安装pyttsx3

Python笔记七:经典例题大田字格,七段数码管绘制,三国演义词频统计及文本朗读_第4张图片

import pyttsx3 
# 模块初始化
txt = open("三国演义.txt","r",encoding='utf-8').read()
# 模块初始化
engine = pyttsx3.init()
volume = engine.getProperty('volume')
# 设置发音大小,范围为0.0-1.0
engine.setProperty('volume', 0.6)
# 设置发音速率,默认值为200
engine.setProperty('rate', 150)
# 设置默认的声音:voices[0].id代表男生,voices[1].id代表女生
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id)
#设置朗读文本
engine.say(txt)
# 等待语音播报完毕
engine.runAndWait()

你可能感兴趣的:(Python学习笔记,python,开发语言,windows)