随机造句工具-曾经四五千块的工资工作的产物现在想想

该博客介绍了一个基于Python实现的随机造句工具,它能根据预设的词集、规则和配置文件生成多样化的句子。工具通过读取词集文件、规则文件和配置文件,动态组合词语,实现了灵活的句子生成。用户可以选择词集、句式和存储路径,适用于多种场景的文本生成需求。
摘要由CSDN通过智能技术生成

1.需求设计

2.代码展示

import tkinter as tk
from tkinter import filedialog
import os
import xlwt
import pandas as pd
import numpy as np
import random
import time
from functools import reduce
import re

class word():
    def __init__(self, word1, word_set, random_number, cycles_number):
        self.word1 = word1
        self.word_set = word_set
        self.random_number = random_number
        self.cycles_number = cycles_number

    """随机选取词语并根据词语中是否含有’{‘返回不同值"""
    def random_run(self):
        random_word = ''
        if self.word1.__str__().__contains__('{') == False:
            return self.word1
        else:
            if (self.cycles_number)<= (self.random_number[self.word1]-1) :
                random_word = random.sample(self.word_set[self.word1],1)
                return random_word
            else:
                random_word = list(self.word_set[self.word1][0])
                return random_word

def word_file():
    """set word path"""
    global word_path #词集文件路径
    word_path = filedialog.askopenfilename(title=u'选择文件', initialdir=(os.path.expanduser('H:/')))
    #print('打开文件:', word_path)
    text1.insert('insert', word_path)
    if word_path != '':
        text4.insert('insert', '----------------已选取词集文件----------------'+'\n')
    return word_path

def rule_file():
    """set rule path"""
    global rule_path  # 句式文件路径
    rule_path = filedialog.askopenfilename(title=u'选择文件', initialdir=(os.path.expanduser('H:/')))
    #print('打开文件:', rule_path)
    text2.insert('insert', rule_path)
    if rule_path != '':
        text4.insert('insert', '----------------已选取规则文件----------------' + '\n')
    return rule_path

def result_file():
    """set result path"""
    global result_path #生成结果路径
    result_path = ''
    result_path = filedialog.askdirectory()
    print(result_path)
    text3.insert('insert', result_path)
    # if result_path != '':
    #     text4.insert('insert', '----------------已选取存储路径----------------' + '\n')
    return result_path

def word_read():
    """reading the word_file and select first row"""
    # data_word = pd.read_excel('D:\调试输入\造句调试\词集名称.xlsx')
    data_word = pd.read_excel(word_path)
    word_df = pd.DataFrame(data_word)
    source_word = list(word_df.loc[:,:])

    des_word = []
    for s in source_word:
        temp = '{'+ str(s) + '}'
        des_word.append(temp)

    """Selecting every columns into list"""
    transfer_df = pd.DataFrame(word_df)
    # print(transfer_df)
    word = []

    for i in range(len(des_word)):
        word1 = transfer_df.iloc[:,[i]]
        word0 = word1.values.flatten().tolist()
        '''remove np.nan'''
        while np.nan in word0:
            word0.remove(np.nan)
        # print(word0)
        word.append(word0)
    # print(word)
    """ dict the dest_word and word"""
    result_word = {}
    for i in range(len(des_word)):
        result_word[des_word[i]] = word[i]
    # print(result_word)
    return result_word

def rule_read():
    """reading the rule_file"""
    # data_rule = pd.read_excel('D:\调试输入\造句调试\句式名称.xlsx')
    data_rule = pd.read_excel(rule_path)
    rule = list(data_rule['句式'])
    return rule

def config_file_read():
    "reading the config file"
    global result_word2
    config_file_path= filedialog.askopenfilename(title=u'选择文件', initialdir=(os.path.expanduser('H:/')))
    text5.insert('insert',config_file_path)
    if config_file_path != '':
        text4.insert('insert', '----------------已选取配置文件----------------' + '\n')
    # word_number_df = pd.read_excel('D:\调试输入\造句调试\词集随机个数.xlsx')
    word_number_df = pd.read_excel(config_file_path)
    word1 = word_number_df.iloc[:,[1]]
    word2 = word1.values.flatten().tolist()  #读取词集内容

    word3 = word_number_df.iloc[:, [0]]
    word4 = word3.values.flatten().tolist() #读取词集名
    word5 = []
    for s in word4:
        temp = '{'+ str(s) + '}'
        word5.append(temp)
    # print(word5)

    """dict word5 and word2"""
    result_word2 = {}
    for i in range(len(word5)):
        result_word2[word5[i]] = word2[i]
    #print(result_word2)

    """get the maximum amount"""
    # global max_amount
    # max_amount = max(word2)

    return result_word2

def combine_word_rule(result_word,rule,result_word2):
    r1 = []
    for g in rule:
        # g = "{送}{数量}{物品}{感谢语}"
        # g = "{送}{明天}{节日}"
        """分割词集"""
        pattern = '({[a-zA-Z0-9_\u4e00-\u9fa5]{1,}})'
        rule_temp1 = re.split(pattern,g)
        while '' in rule_temp1:
            rule_temp1.remove('')
        """拆分句式采用字典数量"""
        used_word_number = []
        for wordx in rule_temp1:
            if wordx.__str__().__contains__('{'):
                used_word_number.append(result_word2[wordx])
        print(used_word_number)
        max_number = max(used_word_number)
        used_multiply = reduce(lambda x,y:x*y,used_word_number)
        divid_number = used_multiply//max_number
        # print(max_number)
        # print(used_multiply)
        """创建词语对象"""

        cycle_count = 1
        while cycle_count:
            str2 = ''
            for x in rule_temp1:
                str1 = ''.join(word(x, result_word, result_word2,cycle_count//divid_number).random_run())
                str2 = str2 + str1
            if str2 not in r1:
                r1.append(str2)
            print(len(r1))
            cycle_count = cycle_count + 1
            if cycle_count == used_multiply:
                break
    print(r1)
    return r1

def progress_run():
    """working in progress"""
    x = word_read()
    z = rule_read()
    # w = config_file_read()
    w = result_word2
    # q = max_amount
    o = combine_word_rule(x, z, w)

    '''get current path and current time'''
    current_path = os.getcwd() + '\\输出结果'  # 获取当前路径
    current_time = time.strftime('%Y-%m-%d %H:%M:%S')  # 获取当前时间
    isExists = os.path.exists(current_path)  # 判断路径是否存在
    a = current_time.replace(' ', '-').replace(':', '-')
    if not isExists:
        os.mkdir(current_path)
        print("创建成功")
    else:
        print(current_path + '目录已经存在')
    c = current_path + '\\'  + a +'-' + 'result.xls'
    #print(c)

    '''save the result in select path or in memeroy path'''
    wb3 = xlwt.Workbook(encoding='utf-8')
    sheet3 = wb3.add_sheet("output")
    q = 0
    try:
        for l in o:
            sheet3.write(q, 0, l)
            q = q + 1
    except BaseException:
        pass

    if result_path == '':
        wb3.save(c)
        text4.insert('insert','----------------已存储结果至默认文件夹---' + '\n')
    else:
        # text4.insert('insert', '----------------已选取存储路径----------------' + '\n')
        wb3.save(result_path+'/result.xls')
        text4.insert('insert','----------------已存储结果至选定文件夹---' + '\n')

    # text4.insert('insert','----------------已生成造句文件----------------'+'\n')

if __name__ == '__main__':
    window = tk.Tk()
    window.title('随机造句工具')  # 标题
    window.geometry('500x400')  # 窗口尺寸
    # window.config(bg = '')
    #file_path = ''              # 词集读入路径

    text1 = tk.Text(window, width=35, height=2, bg='white', font=('Arial', 12))  #显示词集读入路径选择
    text1.pack()
    text1.place(x = 160, y = 20)

    text2 = tk.Text(window, width=35, height=2, bg='white', font=('Arial', 12))  # 显示规则句式读入路径
    text2.pack()
    text2.place(x=160, y=80)

    text3 = tk.Text(window, width=35, height=2, bg='white', font=('Arial', 12))  # 显示自定义存储路径
    text3.pack()
    text3.place(x=160, y=200)

    text5 = tk.Text(window, width=35, height=2, bg='white', font=('Arial', 12))  # 显示配置文件读入路径
    text5.pack()
    text5.place(x=160, y=140)

    text4 = tk.Text(window, width=35, height=6, bg='white', font=('Arial', 12))  # 显示提示信息显示栏
    text4.pack()
    text4.place(x=160, y=260)

    bt1 = tk.Button(window, text='选择词集文件', width=15, height=1,bg = 'Gainsboro', relief ='groove',command=word_file) #词集路径选择按钮
    bt1.pack()
    bt1.place(x = 20,y =20)

    bt2 = tk.Button(window, text='选择句式文件', width=15, height=1,bg = 'Gainsboro', relief ='groove', command=rule_file)  # 词集路径选择按钮
    bt2.pack()
    bt2.place(x=20, y=80)

    bt5 = tk.Button(window, text='结果存储路径', width=15, height=1,bg = 'Gainsboro', relief ='groove', command=result_file)  #结果存储路径按钮
    bt5.pack()
    bt5.place(x=20, y=200)

    bt4 = tk.Button(window, text='运行', width=15, height=2,bg = 'Gainsboro', relief ='groove',command = progress_run)  # 运行按钮
    bt4.pack()
    bt4.place(x=20, y=260)

    bt3 = tk.Button(window, text='选择配置文件', width=15, height=1,bg = 'Gainsboro', relief ='groove', command=config_file_read)  # 配置文件选择按钮
    bt3.pack()
    bt3.place(x=20, y=140)

    window.mainloop()  # 显示

3.结果展示

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值