试图绘制直方图覆盖值

2022-07-06 12:37:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图从电报机器人的列表中绘制直方图。我使用“finallist”,在循环后我清除了我的所有列表,但直方图似乎从以前的输入中获取所有值,并用所有值绘制新的直方图,只改变颜色:

import matplotlib.pyplot as plt
import sys
import time
import telepot
from telepot.loop import MessageLoop
import numpy as np
import pylab as pl
import logging
import os

x = list()
l = list()

def handle(msg):
    content_type, chat_type, chat_id = telepot.glance(msg)
    print(content_type, chat_type, chat_id)
    print("Hi, start typing!")

    if content_type == 'text':
        if msg['text'] == 'clean':
            x.clear()
            bot.sendMessage(chat_id, 'Your list is empty. ')
        else:
            if msg['text'] == 'histogram':
                finallist = l[0]
                i=1
                while i < len(l):
                    finallist = finallist + l[i]
                    i = i+1
                bot.sendMessage(chat_id, 'Here is the list of occuring numbers:' + str(finallist).strip(' '))
                fig = pl.hist(finallist)
                plt.savefig('finalplot.png')
                bot.sendPhoto(chat_id=chat_id, photo=open('finalplot.png', 'rb'))
                bot.sendMessage(chat_id, 'This is your histogram.')
                x.clear()
                finallist.clear()
                l.clear()
                os.remove("finalplot.png")
            else:
                x.append(msg['text'])
                l.append([int(i) for i in str(msg['text'])])
                bot.sendMessage(chat_id, 'Your list is: ' + str(x).strip(' ') + str(l).strip(' '))


TOKEN = 'mytoken'  # get token from command-line

bot = telepot.Bot(TOKEN)
MessageLoop(bot, handle).run_as_thread()
print('Listening ...')

# Keep the program running.
while 1:
    time.sleep(10)


Tags: textimportidisastypebotchatmsglistclearstrtelepotsendmessagefinallist