我使用它Python
从莫斯科交易所导入数据并将其转换为这种格式,但是当我尝试将其加载到程序中时,出现了错误。我该如何修复它?
示例数据:
Date,Time,Last,Volume
20240415,095000,2825.29,27826
20240415,095100,2824.16,24813
20240415,095200,2824.65,15432
我的代码出错了,我不知道哪里出了问题
File "c:\Users\N-2323\Форма регистрации\форма_регистрации.py", line 195, in <module>
bot.polling(none_stop=True, interval=0)
~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\N-2323\AppData\Local\Programs\Python\Python313\Lib\site-packages\telebot\__init__.py", line 1198, in polling
self.__threaded_polling(non_stop=non_stop, interval=interval, timeout=timeout, long_polling_timeout=long_polling_timeout,
~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
logger_level=logger_level, allowed_updates=allowed_updates)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\N-2323\AppData\Local\Programs\Python\Python313\Lib\site-packages\telebot\__init__.py", line 1273, in __threaded_polling
raise e
File "C:\Users\N-2323\AppData\Local\Programs\Python\Python313\Lib\site-packages\telebot\__init__.py", line 1235, in __threaded_polling
self.worker_pool.raise_exceptions()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^
File "C:\Users\N-2323\AppData\Local\Programs\Python\Python313\Lib\site-packages\telebot\util.py", line 150, in raise_exceptions
raise self.exception_info
File "C:\Users\N-2323\AppData\Local\Programs\Python\Python313\Lib\site-packages\telebot\util.py", line 93, in run
task(*args, **kwargs)
~~~~^^^^^^^^^^^^^^^^^
File "c:\Users\N-2323\Форма регистрации\форма_регистрации.py", line 185, in org
img.save('res-cod.png')
^^^^^^^^^^^
AttributeError: 'Image' object has no attribute 'savefig'
Exception ignored in atexit callback <bound method Gcf.destroy_all of <class 'matplotlib._pylab_helpers.Gcf'>>:
File "C:\Users\N-2323\AppData\Local\Programs\Python\Python313\Lib\site-packages\matplotlib\_pylab_helpers.py", line 81, in destroy_all
manager.destroy()
File "C:\Users\N-2323\AppData\Local\Programs\Python\Python313\Lib\site-packages\matplotlib\backends\_backend_tk.py", line 586, in destroy
self.canvas._tkcanvas.after_cancel(self.canvas._idle_draw_id)
File "C:\Users\N-2323\AppData\Local\Programs\Python\Python313\Lib\tkinter\__init__.py", line 894, in after_cancel
data = self.tk.call('after', 'info', id)
RuntimeError: main thread is not in main loop
代码(我留了一段,我觉得里面有一些东西):
import os
import requests
from PIL import Image
from io import BytesIO
import matplotlib.pyplot as plt
import telebot
from datetime import datetime
from telebot import types
from telebot.types import InputMediaPhoto
from matplotlib import pyplot as plt
import ssl
bot = telebot.TeleBot('токен');
if not os.path.exists("users.txt"):
with open("users.txt", "w", encoding="utf-8", errors='ignore') as f:
f.write("Дата | Номер кода | ФИО | Телефон | Почта | Номер на мероприятии | Организация\n")
def add_user(data: dict) -> None:
current_time = datetime.now().strftime("%d.%m.%Y %H:%M")
record = (
f"{current_time} | "
f"{data.get('cod', 'Н/Д')} | "
f"{data.get('fio', 'Н/Д')} | "
f"{data.get('phone', 'Н/Д')} | "
f"{data.get('email', 'Н/Д')} | "
f"{data.get('org_num', 'Н/Д')} | "
f"{data.get('org', 'Н/Д')}\n"
)
with open("users.txt", "a", encoding="utf-8", errors='ignore') as f:
f.write(record)
def format_data(data: dict) -> str:
return (
f"ФИО: {data['fio']}\n"
f"Телефон: {data['phone']}\n"
f"Email: {data['email']}\n"
f"Представитель: {data['org']}"
)
def generate_barcode(cod):
url = 'https://barcode.tec-it.com/barcode.ashx'
params = {
'data': cod,
'multiplebarcodes': 'true',
'translate-esc': 'on'
}
response = requests.get(url, params=params, verify=False)
if response.status_code == 200:
image = Image.open(BytesIO(response.content))
return image
else:
# Raise an exception if the request failed
raise Exception(f'Failed to generate barcode. Status code: {response.status_code}')
def main(login: str):
print(f'Привет, {login}!')
@bot.message_handler(commands=['start'])
def start(message):
markup = types.ReplyKeyboardRemove(selective=False)
bot.send_message(message.chat.id, 'Добро пожаловать! Зарегистрируйтесь на мероприятие.', reply_markup=markup)
bot.send_message(message.chat.id, "Введите ваше ФИО: ")
bot.register_next_step_handler(message, fio, data={})
.....
def email(message, data):
data["email"] = message.text.strip()
print(data["email"])
markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
btn1 = types.KeyboardButton("1")
btn2 = types.KeyboardButton("2")
btn3 = types.KeyboardButton("3")
markup.add(btn1, btn2, btn3)
bot.send_message(message.chat.id, '''Выберите, какую роль Вы будете принимать на мероприятии:
1. Фирма экономической игры
2. Участник фестиваля
3. Гости ''', reply_markup=markup)
bot.register_next_step_handler(message, org_num, data=data)
def org_num(message, data):
data["org_num"] = message.text.strip()
if data["org_num"] == "1":
print(data["org_num"])
markup = types.ReplyKeyboardRemove(selective=False)
Vorg = bot.send_message(message.chat.id, 'Название вашей фирмы: ' , reply_markup=markup)
bot.register_next_step_handler(message, org, data=data)
elif data["org_num"] == "3":
print(data["org_num"])
markup = types.ReplyKeyboardRemove(selective=False)
bot.send_message(message.chat.id, 'Напишите "Гость" : ', reply_markup=markup)
bot.register_next_step_handler(message, org, data=data)
elif data["org_num"] == "2":
print(data["org_num"])
markup = types.ReplyKeyboardRemove(selective=False)
bot.send_message(message.chat.id, 'Название вашей группы: ', reply_markup=markup)
bot.register_next_step_handler(message, org, data=data)
else:
bot.send_message(message.chat.id, 'Напишите цифру от 1 до 3!')
bot.send_message(message.chat.id, '''Выберите, какую роль Вы будете принимать на мероприятии:
1. Фирма экономической игры
2. Участник фестиваля
3. Гости ''')
bot.register_next_step_handler(message, org_num, data=data)
def org(message, data):
data["org"] = message.text.strip()
print(data["org"])
line_count = sum(1 for line in open('users.txt', encoding="utf-8", errors='ignore'))
cod_num = 60000 + line_count
cod_num = str(cod_num)
cod = '522' + cod_num +'87'
data["cod"] = cod
print(data["cod"])
add_user(data)
bot.send_message(message.chat.id, "Регистрация прошла успешно!")
bot.send_message(message.chat.id, f"Ваши данные сохранены:\n{format_data(data)}")
# Generate the barcode
barcode_image = generate_barcode(cod)
# Display the barcode
plt.imshow(barcode_image)
plt.savefig('cod.png')
img = Image.open('cod.png')
img = img.crop((79, 104, img.width-62, img.height-98))
img.save('res-cod.png')
file = open('res-cod.png', 'rb')
bot.send_photo(message.chat.id, file)
bot.send_message(message.chat.id, '''Сохраните этот штрих-код!
Если хотите зарегистрировать кого-то ещё, напишите /start''')
bot.polling(none_stop=True, interval=0)
if __name__ == '__main__':
main()
我发现该错误似乎来自一个用户。也就是说,一个注册了,给了他一个代码,第二个刚刚注册,由于错误没有给出代码。
该代码是一个简单的控制台应用程序,用于随机更新汇率。我按照我的训练计划编写了它,并在这段代码中实现了delegate
和event
。版本.NET
- 4.8
代码写得有多糟糕?应该做出哪些改变?
using System;
using System.Collections.Generic;
namespace CryptoBot
{
public class Program
{
public static Dictionary<string, decimal> CryptoValute = new Dictionary<string, decimal>();
public static decimal ForExtemeValue;
private static int _count = 0;
static CryptoPriceMonitor priceMonitor = new CryptoPriceMonitor();
static TraderBot traderBot = new TraderBot(priceMonitor);
public static void PrintColor(string message, ConsoleColor color)
{
Console.ForegroundColor = color;
Console.WriteLine(message);
Console.ResetColor();
}
static void Main(string[] args)
{
CryptoValute.Add("Bitcoin", 50000);
CryptoValute.Add("DogeCoin", 3);
CryptoValute.Add("Ethereum", 1680);
CryptoValute.Add("USDT", 26);
PrintColor("Choose valute: Bitcoin, DogeCoin, Ethereum, USDT", ConsoleColor.Green);
PrintColor("Current Prices:", ConsoleColor.Green);
foreach (var price in CryptoValute)
{
Console.WriteLine(price);
}
string Choose = Console.ReadLine();
while (true)
{
switch (Choose)
{
case "Bitcoin":
ForExtemeValue = CryptoValute["Bitcoin"];
Iterations("Bitcoin");
Choose = Console.ReadLine();
break;
case "DogeCoin":
ForExtemeValue = CryptoValute["DogeCoin"];
Iterations("DogeCoin");
Choose = Console.ReadLine();
break;
case "Ethereum":
ForExtemeValue = CryptoValute["Ethereum"];
Iterations("Ethereum");
Choose = Console.ReadLine();
break;
case "USDT":
ForExtemeValue = CryptoValute["USDT"];
Iterations("USDT");
Choose = Console.ReadLine();
break;
default:
PrintColor("There is no currency on the list.", ConsoleColor.Green);
Choose = Console.ReadLine();
break;
}
}
}
private const int IterationsCount = 1000;
public static void Iterations(string name)
{
string valute;
decimal value;
_count = 0;
valute = name;
value = CryptoValute[name];
while (_count != IterationsCount)
{
_count++;
value = CryptoValute[name];
priceMonitor.UpdatePrice(value, valute);
}
Console.Clear();
PrintColor($"Here are a {IterationsCount} last iterations", ConsoleColor.Green);
PrintColor("Choose valute: Bitcoin, DogeCoin, Ethereum, USDT", ConsoleColor.Green);
PrintColor("Current Prices:", ConsoleColor.Green);
foreach (var price in CryptoValute)
{
Console.WriteLine(price);
}
}
}
public class CryptoPriceMonitor
{
public void UpdatePrice(decimal oldPrice, string name)
{
decimal currentPrice = oldPrice;
PriceChanged?.Invoke(oldPrice, ExtremeValues(currentPrice), name);
}
private Random _random = new Random();
private int _procent;
private const int MaxRandomProcent = 8;
private const int MinRandomProcent = -7;
private decimal ExtremeValues(decimal basePrice)
{
decimal newPrice = basePrice;
decimal maxValue = Program.ForExtemeValue * 100;
decimal minValue = Program.ForExtemeValue - (Program.ForExtemeValue * 90) / 100;
if (basePrice >= maxValue)
{
_procent = _random.Next(MinRandomProcent, 0);
newPrice -= (basePrice * Math.Abs(_procent)) / 100;
return newPrice;
}
if (basePrice <= minValue)
{
_procent = _random.Next(1, MaxRandomProcent);
newPrice += (basePrice * Math.Abs(_procent)) / 100;
return newPrice;
}
else
{
_procent = _random.Next(MinRandomProcent, MaxRandomProcent);
if (_procent > 0)
{
newPrice += (basePrice * Math.Abs(_procent)) / 100;
return newPrice;
}
else
{
newPrice -= (basePrice * Math.Abs(_procent)) / 100;
return newPrice;
}
}
}
public delegate void PriceChangeHandler(decimal oldPrice, decimal newPrice, string valute);
public event PriceChangeHandler PriceChanged;
}
public class TraderBot
{
public TraderBot(CryptoPriceMonitor monitor)
{
monitor.PriceChanged += OnPriceChanged;
}
public void OnPriceChanged(decimal oldPrice, decimal newPrice, string valute)
{
if (newPrice > oldPrice)
{
Program.PrintColor($"Цена повысилась: {oldPrice} -> {newPrice}", ConsoleColor.Green);
RestorPrice(valute, newPrice);
}
else
{
Program.PrintColor($"Цена понизилась: {oldPrice} -> {newPrice}", ConsoleColor.Red);
RestorPrice(valute, newPrice);
}
}
public static void RestorPrice(string valute, decimal value)
{
Program.CryptoValute[valute] = value;
}
}
}
我将一个数组传递给该方法,第一次它显示所有内容,但它不会再次运行。
我在其中创建了第二个数组,对吗?这是为什么?
void Main()
{
int[] names = new int[] { 1, 2, 3, 4 };
Calc(names);
names [0] = 9;
Calc(); //Здесь он не запускается
Console.WriteLine("end");
}
void Calc(params int[] mars)
{
int[] pars = new int[mars.Length];
for (int i = 0; i < mars.Length; i++)
{
pars[i] = mars[i];
Console.WriteLine(pars[i]);
}
}
任务:https://www.codewars.com/kata/535742c7e727388cdc000297/train/python
您需要生成一副 52 张牌的牌 - 四种花色,每花色 13 张牌。
牌的等级是:A、二、三、四、五、六、七、八、九、十、J、Q、K
结论应该是这样的
地图的每一行都将采用以下格式
"ace of hearts"
"ace of spades"
"ace of diamonds"
"ace of clubs"
他们不必按顺序进行。
附加限制 - 仅一行
一行代码不通过
import random
dict_card_format = {1: "hearts", 2: "spades", 3: "diamonds", 4: "clubs"}
dict_rank = {1: "ace", 2: "two", 3: "three", 4: "four", 5: "five", 6: "six", 7: "seven",
8: "eight", 9: "nine", 10: "ten", 11: "jack", 12: "queen", 13: "king"
}
nums = list(range(1, 5))
random.shuffle(nums)
nums1 = list(range(1, 14))
random.shuffle(nums1)
def deck_of_cards():
return [f"{''.join(dict_rank[j])} of {''.join(dict_card_format[i])}" for j in nums1 for i in nums]
由 CodesWars 服务器发布
Test Results:
Code lines
Tests
1 line only!: 13 should equal 1 - этот Тест не проходит
Completed in 0.09ms
Completed in 0.14ms
Sample tests - этот Тест проходит
Tests
如果单行代码不起作用,那么如何在一行中输出函数输出?
我尝试用不同的方式写它
def deck_of_cards():
n_card_format = 4
n_rank = 13
nums = list(range(1, 5))
random.shuffle(nums)
card_format = nums[:4]
nums1 = list(range(1, 14))
random.shuffle(nums1)
rank_list = nums1[:13]
# s = ""
lst = []
for i in card_format:
for j in rank_list:
if i in dict_card_format and j in dict_rank:
lst.append(f"{''.join(dict_rank[j])} of {''.join(dict_card_format[i])}")
# lst.append(''.join(dict_rank[j]) + " " + "of" + " " + ''.join(dict_card_format[i]))
# s += (''.join(dict_rank[j]) + " " + "of" + " " + ''.join(dict_card_format[i]) + " ")
# s += "\n"f"{''.join(dict_rank[j])} of {''.join(dict_card_format[i])} "
return lst
帮我找到正确的解决方案