filename = './test.txt'
table = dict()
cnt = 0
with open(filename) as file:
    for line in file:
        l = line.strip()
        for c in line:
            if not c.isalpha():
                continue
            else:
                cnt+=1
                if c in table:
                    table[c]+=1
                else:
                    table[c] = 1

for key in table.keys():
    table[key]/=cnt
print(table)
Python-basis/2.6.1.py
dadwadw233/NPU-ApplicationIntegrateExpriment

import random
import string

def generate_questions(file_path, n):
    with open(file_path, 'w') as file:
        for i in range(1, n+1):
            question = f"{i}.{generate_random_string(random.randint(1, 50))}\n"
            file.write(question)

def generate_random_string(length):
    characters = string.ascii_letters + string.digits
    return ''.join(random.choice(characters) for _ in range(length))

def generate_answer(file_path, n):
    with open(file_path, 'w') as file:
        for i in range(1, n + 1):
            answer = f"{i}.{generate_random_string(random.randint(1, 200))}\n"
            file.write(answer)



def generate_paper(path, questions, answers, n):
    with open(path, 'w') as f:
        indexes = random.sample(range(0, len(questions)), n)
        for i in range(n):
            question = questions[indexes[i]].split('.')[1]
            answer = answers[indexes[i]].split('.')[1]
            content = f"{i+1}.{question}\nanswer: {answer}\n\n"
            f.write(content)


questions_path = './questions.txt'
answers_path = './answer.txt'

generate_questions(questions_path, 1000)
generate_answer(answers_path, 1000)

# process data
questions = []
answers = []

with open(questions_path) as f:
    for line in f:
        questions.append(line.strip())

with open(answers_path) as f:
    for line in f:
        answers.append(line.strip())

generate_paper('./paper.txt', questions, answers, 10)
Python-basis/2.6.2.py
dadwadw233/NPU-ApplicationIntegrateExpriment
import string
from collections import Counter


def count_word_frequency(file_path):
    with open(file_path, 'r') as file:
        text = file.read()

    translator = str.maketrans('', '', string.punctuation)
    words = text.translate(translator).split()
    word_count = Counter(words)

    return word_count


file_path = "./test.txt"
result = count_word_frequency(file_path)

for word, count in result.items():
    print(f"{word}: {count}")

Python-basis/3.5.1.py
dadwadw233/NPU-ApplicationIntegrateExpriment
import imaplib
import email
from email.header import decode_header
import time

def get_email_body(msg):
    body = ""
    if msg.is_multipart():
        for part in msg.walk():
            if part.get_content_type() == "text/plain":
                body += part.get_payload(decode=True).decode()
    else:
        body = msg.get_payload(decode=True).decode()
    return body

def check_email(server, username, password):
    try:
        imap_server = imaplib.IMAP4_SSL(server)
        imap_server.login(username, password)
        imap_server.select("inbox")
        result, data = imap_server.search(None, "UNSEEN")
        email_ids = data[0].split()
        unread_count = len(data[0].split())
        print(f"未读邮件数量：{unread_count}")
        if email_ids:
            latest_email_id = email_ids[-1]
            result, msg_data = imap_server.fetch(latest_email_id, "(RFC822)")
            raw_email = msg_data[0][1]

            msg = email.message_from_bytes(raw_email)
            subject, encoding = decode_header(msg["Subject"])[0]
            if isinstance(subject, bytes):
                subject = subject.decode(encoding or "utf-8")
            from_ = msg.get("From")
            email_body = get_email_body(msg)
            print(f"最新邮件主题：{subject}")
            print(f"发件人：{from_}")
            print("邮件正文：")
            #print(email_body)
        else:
            print("没有未读邮件")

        # 关闭连接
        imap_server.logout()

    except Exception as e:
        print(f"检查邮件时出错：{str(e)}")


# 用户输入邮箱账号信息
server = 'imap.gmail.com'
username = 'yuanhongyu.me@gmail.com'
password = '*****'

# 每隔一段时间检查一次
while True:
    check_email(server, username, password)
    #time.sleep(0.1)  # 等待1小时后再次检查

Python-basis/3.5.3.py
dadwadw233/NPU-ApplicationIntegrateExpriment
import pymysql
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
import urllib
import urllib.request
import hashlib

def md5(str):
    import hashlib
    m = hashlib.md5()
    m.update(str.encode("utf8"))
    return m.hexdigest()

statusStr = {
    '0': '短信发送成功',
    '-1': '参数不全',
    '-2': '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间',
    '30': '密码错误',
    '40': '账号不存在',
    '41': '余额不足',
    '42': '账户已过期',
    '43': 'IP地址限制',
    '50': '内容含有敏感词'
}

smsapi = "https://api.smsbao.com/"

user = 'dadwadw'

password = md5('*****')

def send_message(phone, content):
    data = urllib.parse.urlencode({'u': user, 'p': password, 'm': phone, 'c': content})
    send_url = smsapi + 'sms?' + data
    response = urllib.request.urlopen(send_url)
    the_page = response.read().decode('utf-8')
    print (statusStr[the_page])
def create_database(name, cur):
    try:
        cur.execute(f"CREATE DATABASE IF NOT EXISTS {name}")
        print(f"create database: {name} successfully")
    except Exception as e:
        print(f"error: {e}")


def create_table(name, cur):
    try:
        cur.execute(f"""
            CREATE TABLE IF NOT EXISTS {name} (
                id INT AUTO_INCREMENT PRIMARY KEY,
                time DATETIME,
                content TEXT
            )
        """)
        print(f"create table: {name} successfully")
    except Exception as e:
        print(f"error: {e}")

def add_event(time, event, cur, table):
    try:
        cur.execute(f"INSERT INTO `{table}` (`time`, `content`) VALUES (%s, %s)", (time, event))
        print(f"create event successfully")
    except Exception as e:
        print(f"error: {e}")
pymysql_config = {
    'host': 'cd-cdb-7b2ydzz4.sql.tencentcdb.com',
    'port': 63937,
    'user': 'root',
    'password': '*****',
    'charset': 'utf8',
}

conn = pymysql.connect(**pymysql_config)
cur = conn.cursor()

print("是否创建一个新的数据库（建议不要qaq）？（Y/N）")
choice = input()
if choice == "Y" or choice == 'y':
    name = input("输入数据库名称： ")
    create_database(name, cur)

database = input("输入你要使用的数据库： ")
pymysql_config = {
    'host': 'cd-cdb-7b2ydzz4.sql.tencentcdb.com',
    'port': 63937,
    'user': 'root',
    'password': '******',
    'database': database,
    'charset': 'utf8',
}
conn = pymysql.connect(**pymysql_config)
cur = conn.cursor()
print("是否创建一个新表（建议不要qaq）？（Y/N）")
choice = input()

if choice == "Y" or choice == 'y':
    name = input("输入表名： ")
    create_table(name, cur)

table = input("输入你要使用的表： ")
# INSERT INTO `test1` (`id`, `time`, `content`) VALUES (1, '2023-10-05 21:02:43', '11111');
running = True
while running:
    choice = input("选择操作（1：新建待办实事项; 2: 发送所有待办事项到手机; 3:发送所有信息到邮箱; 4：退出（其他的还没写qaq））： ")
    if choice == '1':
        time = input("输入待办事项日期（xxxx-xx-xx xx:xx:xx）: ")
        event = input("输入待办内容： ")
        add_event(time, event, cur, table)
        conn.commit()
    elif choice == '2':
        phone = input("输入手机号（中国大陆）： ")
        cur.execute(f"SELECT * FROM `{table}`")
        records = cur.fetchall()

        formatted_records = ""
        for record in records:
            datetime_str = record[1].strftime("%Y-%m-%d %H:%M:%S")
            content = record[2]
            formatted_records += f"{datetime_str}: {content}\n"
        send_message(phone, formatted_records)

    elif choice == '3':
        email = input("输入邮箱： ")
        cur.execute(f"SELECT * FROM `{table}`")
        records = cur.fetchall()
        sender_email = "yuanhongyu.me@gmail.com"
        password = "ysut mmet dcqq xszf"
        formatted_records = ""
        for record in records:
            datetime_str = record[1].strftime("%Y-%m-%d %H:%M:%S")
            content = record[2]
            formatted_records += f"{datetime_str}: {content}\n"
        subject = '待办提醒'
        message = formatted_records
        msg = MIMEMultipart()
        msg['From'] = sender_email
        msg['To'] = email
        msg['Subject'] = subject
        msg.attach(MIMEText(message, 'plain'))
        try:
            server = smtplib.SMTP('smtp.gmail.com', 587)
            server.starttls()
            server.login(sender_email, password)
            # 发送邮件
            server.sendmail(sender_email, email, msg.as_string())
            print('邮件发送成功！')

        except Exception as e:
            print('邮件发送失败:', str(e))

        finally:
            server.quit()
    else:
        break
Python-basis/3.5.4.py
dadwadw233/NPU-ApplicationIntegrateExpriment
import matplotlib.pyplot as plt
from collections import Counter
import string



def read_text_file(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        text = file.read()
    return text


def count_words(text):
    translator = str.maketrans('', '', string.punctuation)
    words = text.translate(translator).split()
    word_counts = Counter(words)
    return word_counts


def choose_word_colors(word_counts):
    sorted_word_counts = dict(sorted(word_counts.items(), key=lambda item: item[1], reverse=True))
    max_count = max(sorted_word_counts.values())

    colors = []
    for word, count in sorted_word_counts.items():
        normalized_count = count / max_count
        color = plt.cm.RdYlBu(normalized_count)
        colors.append(color)

    word_colors = {word: color for word, color in zip(sorted_word_counts.keys(), colors)}
    return word_colors

def plot_word_frequency(word_counts, word_colors, top_n=10):
    most_common_words = word_counts.most_common(top_n)
    words, counts = zip(*most_common_words)
    colors = [word_colors[word] for word in words]

    plt.figure(figsize=(19, 8))
    bars = plt.bar(words, counts, color=colors)
    plt.xlabel('words')
    plt.ylabel('frequency')
    plt.title(f'top {top_n} words')
    plt.xticks(rotation=45)


    color_patches = [plt.Rectangle((0, 0), 1, 1, color=color) for color in colors]
    plt.legend(color_patches, words, title="words", loc="upper right", bbox_to_anchor=(1.15, 1))

    plt.tight_layout()
    plt.show()

if __name__ == "__main__":
    file_path = "../Python-basis/test.txt"
    text = read_text_file(file_path)
    word_counts = count_words(text)
    word_colors = choose_word_colors(word_counts)
    plot_word_frequency(word_counts, word_colors, 30)

Python-caculation/5.4.1.py
dadwadw233/NPU-ApplicationIntegrateExpriment
import requests
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime
import time

timestamps = []
prices = []

refresh_interval = 1

plt.figure(figsize=(12, 6))

while True:
    try:
        response = requests.get("https://api.coindesk.com/v1/bpi/currentprice.json")
        data = response.json()
        price_in_usd = float(data["bpi"]["USD"]["rate"].replace(",", ""))  # 提取美元价格
        timestamp = datetime.now()

        timestamps.append(timestamp)
        prices.append(price_in_usd)

        if len(prices) >= 2:
            price_change = prices[-1] - prices[-2]
            if price_change > 0:
                line_color = 'g'
            elif price_change < 0:
                line_color = 'r'
            else:
                line_color = 'b'

            plt.clf()
            plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%H:%M:%S'))
            plt.plot(timestamps, prices, marker='o', color=line_color, label='BTC')
            plt.gcf().autofmt_xdate()
            plt.title('Bitcoin Price Trend')
            plt.xlabel('Time')
            plt.ylabel('Price (USD)')
            plt.grid(True)

            plt.annotate(f'{price_in_usd:.2f} USD', (timestamp, price_in_usd), textcoords="offset points",
                         xytext=(0, 10), ha='center')

            plt.legend()
            plt.tight_layout()
            plt.draw()
            plt.pause(refresh_interval)

    except Exception as e:
        print(f"发生错误：{e}")

    time.sleep(refresh_interval)



Python-caculation/5.4.2.py
dadwadw233/NPU-ApplicationIntegrateExpriment