コード例 #1
0
ファイル: app.py プロジェクト: nicodemus-opon/ccsats
def finalizer(filed=[]):
    files = [
        "static/merge/planning and organising.docx",
        "static/merge/customer service.docx", "static/merge/leadership.docx",
        "static/merge/commercial awareness.docx",
        "static/merge/initiative.docx",
        "static/merge/persuasive oral communication.docx"
    ]
    output_doc = Document("static/merge/nicopon.docx")
    for file in filed:
        if file in files:
            pass
        else:
            files.append(file)
    for index, file in enumerate(files):
        try:
            input_doc = Document(file)
            paro = 0
            if index < len(files):
                output_doc.add_page_break()
            for para in input_doc.paragraphs:
                get_para_data(output_doc, para, paro)
                paro += 1
        except Exception as e:
            print("mhhh")
            print(e)
    p = output_doc.add_paragraph()
    r = p.add_run()
    r.add_picture('static/end.PNG', width=Inches(7.09), height=Inches(8.76))
    output_doc.save('static/merge/report.docx')
コード例 #2
0
 def it_has_part_as_header_part(self):
     document = Document(dir_pkg_path)
     header = document.add_header()
     paragraph = header.add_paragraph()
     run = paragraph.add_run()
     run.add_floating_picture(python_powered_path)
     document.save('/home/daniel/faboozle.docx')
コード例 #3
0
 def putIntoDocumentFiles(folderAddress, pic):
     document = Document()
     table = document.add_table(rows=100, cols=4)  #ROWS=25 For 100 barcodes
     for row in table.rows:
         for cell in row.cells:
             paragraph = cell.paragraphs[0]
             run = paragraph.add_run()
             run.add_picture(
                 folderAddress + "\\" + pic + ".png",
                 width=350000 * 0.71,
                 height=350000 * 0.49
             )  #(width,height)=>dimensions(singleTableRow,singleTableColumn) for singlePage
     document.save(folderAddress + "\\singleFolder" + "\\" + pic + "_" +
                   "1" + ".docx")
コード例 #4
0
 def fasterSolution(folderAddress, pic, progress):
     progress['value'] = time.time() - start_time
     progress.update()
     document = Document()
     COLUMNS = 4
     ROWS = 1000
     table = document.add_table(rows=ROWS, cols=COLUMNS)
     table_cells = table._cells
     for i in range(ROWS):
         row_cells = table_cells[i * COLUMNS:(i + 1) * COLUMNS]
         for cell in row_cells:
             paragraph = cell.paragraphs[0]
             run = paragraph.add_run()
             run.add_picture(folderAddress + "\\" + pic + ".png",
                             width=350000 * 0.71,
                             height=350000 * 0.49)
     progress['value'] = time.time() - start_time
     progress.update()
     document.save(folderAddress + "\\" + "singleFolder" + "\\" + pic +
                   "_" + str(1) + ".docx")
     progress['value'] = time.time() - start_time
     progress.update()
コード例 #5
0
def main(directory, file_name):

    if not directory:
        return
    if not file_name:
        file_name = 'test'

    document = Document()
    total_lines = 0
    for root, dirs, fs in os.walk(directory):
        for f in fs:
            suffix = os.path.splitext(f)[1]
            if suffix not in [".java", ".py", ".js", ".go", ".css", ".html", ".cpp", ".h"]:
                continue

            fpath = os.path.join(root, f)
            with open(fpath, "r") as fp:
                try:
                    lines = fp.readlines()
                except Exception as e:
                    print(fpath)
                    continue

                for line in lines:
                    line = line.strip("\n").strip("\r\n")
                    if not line:
                        continue
                    if "__author__ " in line or "__datetime__" in line:
                        continue

                    if total_lines > 3500:
                        break
                    document.add_paragraph(line)
                    total_lines += 1

    document.save(file_name+".docx")
コード例 #6
0
ファイル: app.py プロジェクト: nicodemus-opon/ccsats
def merger(docs=[]):
    list_of_data = []
    list_of_names = []
    for z in docs:
        name = z.split(".")
        na = name[0]
        list_of_names.append(na)
    list_of_names = session["docies"]
    for x in docs:
        list_of_data.append(read_table(x))
    #documentx = Document("static/merge/nicopon.docx")
    y = 0
    x = 0
    op = list_of_data
    list_of_comments = []
    k = 0
    m = 0
    for x in range(len(op)):
        templist = []
        for y in op[x]:
            kk = y['comments']
            kk = str(kk).replace("+", "")
            kk = str(kk).replace("-", "")
            templist.append(kk)
        list_of_comments.append(templist)

    list_of_titles = []
    for x in range(len(op)):
        templist = []
        print(x)
        for y in op[x]:
            print(y['title'])
            templist.append(y['title'])
        list_of_titles.append(templist)
    post = 0
    print(list_of_titles)
    #return(0)
    list_of_filex = []
    for x in range(len(list_of_titles)):
        for y in range(len(list_of_titles[x])):
            if x == 0:
                if list_of_titles[x][y] in list_of_titles[1]:
                    nn = list_of_titles[x][y]
                    ind = list_of_titles[x + 1].index(nn)
                    ti = list_of_titles[x][y]
                    ti = ti.split("\n")
                    ti = ti[0]
                    titi = "static/merge/" + str(ti) + ".docx"
                    titi = titi.lower()
                    list_of_filex.append(titi)
                    documentx = Document()
                    documentx.add_heading(list_of_titles[x][y])
                    i = 0
                    while i < len(list_of_titles):
                        head = list_of_names[i] + '\n'
                        p = documentx.add_paragraph('\n')
                        p.add_run(head).bold = True
                        if i == 0:
                            p.add_run(list_of_comments[x][y])
                        else:
                            p.add_run(list_of_comments[x + 1][ind])
                        i += 1
                    documentx.save(titi)
                else:
                    ti = list_of_titles[x][y]
                    ti = ti.split("\n")
                    ti = ti[0]
                    titi = "static/merge/" + ti + ".docx"
                    titi = titi.lower()
                    list_of_filex.append(titi)
                    documentx = Document()
                    documentx.add_heading(list_of_titles[x][y])
                    head = list_of_names[x] + '\n'
                    p = documentx.add_paragraph('\n')
                    p.add_run(head).bold = True
                    p.add_run(list_of_comments[x][y])
                    documentx.save(titi)
            else:
                if list_of_titles[x][y] in list_of_titles[0]:
                    pass
                else:
                    ti = list_of_titles[x][y]
                    ti = ti.split("\n")
                    ti = ti[0]
                    titi = "static/merge/" + str(ti) + ".docx"
                    titi = titi.lower()
                    list_of_filex.append(titi)
                    documentx = Document()
                    documentx.add_heading(list_of_titles[x][y])
                    head = list_of_names[x] + '\n'
                    p = documentx.add_paragraph('\n')
                    p.add_run(head).bold = True
                    p.add_run(list_of_comments[x][y])
                    documentx.save(titi)
    print("kkk")
    print(list_of_filex)
    finalizer(list_of_filex)
コード例 #7
0
ファイル: parser.py プロジェクト: levdavid/moms_parsers
for hero in heroes:
    hero_doc = Document()

    hero_doc.add_heading(hero, level=1)

    table = hero_doc.add_table(rows=1, cols=4)
    table.style = 'TableGrid'

    hdr_cells = table.rows[0].cells
    hdr_cells[0].text = unicode('Номер сцены', 'utf-8')
    hdr_cells[0].width = 1097280
    hdr_cells[1].text = unicode('Описание', 'utf-8')
    hdr_cells[1].width = 4846320
    hdr_cells[2].text = unicode('Персонажи', 'utf-8')
    hdr_cells[2].width = 2423160
    hdr_cells[3].text = unicode('Примечания', 'utf-8')
    hdr_cells[3].width = 20583680
    for row in data:
        if hero in u''.join(row[4]):
            row_cells = table.add_row().cells
            row_cells[0].width = 1097280
            row_cells[1].width = 4846320
            row_cells[2].width = 2423160
            row_cells[3].width = 20583680

            row_cells[0].text = u''.join(row[0])
            row_cells[1].text = u''.join(row[1])
            row_cells[2].text = u''.join(row[4])

    hero_doc.save(unicode('серия_13', 'utf-8') + "_" + hero + '.docx')
コード例 #8
0
    #   rows which needs to be added to original table
    # for i in range(rows_to_add):
    #     row = tbl.add_row()
    #     row.height_rule = WD_ROW_HEIGHT.EXACTLY
    #     row.height = Pt(24)
    for i in range(rows_to_add):
        tbl.add_row()
    ordered_players = []
    for i in dd.keys():
        ordered_players.append([dd[i]['PUNKTY'], dd[i]['LRT'], i])
    ordered_players = sorted(sorted(sorted(ordered_players,
                                           key=lambda x: x[2]),
                                    key=lambda x: x[1]),
                             key=lambda x: x[0],
                             reverse=True)
    key_order = ['RANKING', 'RUCH', 'ZAWODNIK', 'PUNKTY', 'LRT']
    for i, row in enumerate(tbl.rows[1:]):
        for j, cell in enumerate(row.cells):
            cell.text = str(dd[ordered_players[i][2]][key_order[j]])
    # for i in paragraphs:
    #   print(i.text)


table_creating(data, table, rows_needed)

paragraphs = document.paragraphs
paragraphs[1].text = 'KLASYFIKACJA OPEN MĘŻCZYZN\nNA DZIEŃ ' + datetime.now(
).strftime('%d.%m.%Y')

document.save(datetime.now().strftime('%d.%m.%Y ') +
              'KLASYFIKACJA V GPSWA MĘŻCZYZN.docx')
コード例 #9
0
ファイル: guiSixth.py プロジェクト: prakHr/tkinter-barcode
class ThreadingExample(object):
    """ Threading example class
    The run() method will be started and it will run in the background
    until the application exits.
    """

    #function downloads youtube video with audio or silence according to a variable named youtube_audio_var
    #if empty url is inserted or wrong pattern matching url is inserted, throws error to textBox accordingly
    def download_youtube_video_with_audio(self):
        video_url = self.youtube_url_var.get()
        yav = self.youtube_audio_var.get()
        if video_url == '':
            self.textBox.insert(1.0, "Empty URL inserted" + "\n")
        else:
            p = re.compile(
                r'^(http(s)?:\/\/)?((w){3}.)?youtu(be|.be)?(\.com)?\/.+')
            m = p.match(video_url)
            if m:
                try:
                    if yav == True:
                        stream1 = YouTube(video_url).streams.filter(
                            progressive=yav)
                        if stream1 == [] or stream1 == None:
                            self.textBox.insert(
                                1.0,
                                "Choose without audio instead of  progressive(video and audio):"
                                + "\n")
                        else:
                            stream1[0].download(self.folderAddress)
                            self.textBox.insert(
                                1.0,
                                "Video finished downloading: " + video_url +
                                " : " + "with audio :" + str(yav) + "\n")
                    elif yav == False:
                        stream2 = YouTube(video_url).streams.filter(
                            adaptive=not yav)
                        if stream2 == [] or stream2 == None:
                            self.textBox.insert(
                                1.0,
                                "Choose with audio instead of  adaptive(video):"
                                + "\n")
                        else:
                            stream2[0].download(self.folderAddress)
                            #YouTube(video_url).streams.first().download(self.folderAddress)
                            self.textBox.insert(
                                1.0, "Video finished downloading: " +
                                video_url + " : " + "without audio :" +
                                str(not yav) + "\n")
                except Exception as e:
                    self.textBox.insert(1.0, str(e) + "\n")
                self.youtube_url.delete(0, 'end')
            else:

                self.textBox.insert(1.0,
                                    "Invalid url for download inserted" + "\n")

    #function downloads youtube video between the available resolutions
    #if empty url is inserted or wrong pattern matching url is inserted, throws error to textBox accordingly
    def download_youtube_video(self):
        video_url = self.youtube_url_var.get()
        youtube_res = self.youtube_var.get()

        if video_url == '':
            self.textBox.insert(1.0, "Empty URL inserted" + "\n")
        else:
            p = re.compile(
                r'^(http(s)?:\/\/)?((w){3}.)?youtu(be|.be)?(\.com)?\/.+')
            m = p.match(video_url)
            if m:
                try:
                    stream = YouTube(video_url).streams.get_by_resolution(
                        youtube_res)
                    if stream == [] or stream == None:
                        self.textBox.insert(
                            1.0, "Choose another resolution instead of  :" +
                            youtube_res + "\n")
                    else:
                        stream.download()
                        #YouTube(video_url).streams.first().download(self.folderAddress)
                        self.textBox.insert(
                            1.0, "Video finished downloading: " + video_url +
                            " : " + youtube_res + "\n")
                except Exception as e:
                    self.textBox.insert(1.0, str(e) + "\n")
                self.youtube_url.delete(0, 'end')
            else:

                self.textBox.insert(1.0,
                                    "Invalid url for download inserted" + "\n")

    #function makes a folder named singleFolder if doesn't exists and put corresponding documents of barcodes
    #code_128 barcodes are taken as input from two label above and then given as input to another function
    #sub functions are defined as putIntoDocumentFiles and a faster version of it
    def action(self):
        def makeFolder(self):
            try:
                os.mkdir(self.folderAddress + "\\" + self.directoryName)
            except FileExistsError:
                pass

        self.makeFolder = makeFolder(self)

        self.Code_128 = "code128"
        self.letter_words_1 = self.gender_var.get()
        self.letter_words_2 = self.gender_var_2.get()

        def fasterSolution(self, b):
            self.document = Document()
            self.COLUMNS = 4
            self.ROWS = 100
            self.table = self.document.add_table(rows=self.ROWS,
                                                 cols=self.COLUMNS)
            self.table_cells = self.table._cells
            for i in range(self.ROWS):
                self.row_cells = self.table_cells[i * self.COLUMNS:(i + 1) *
                                                  self.COLUMNS]
                for cell in self.row_cells:
                    self.paragraph = cell.paragraphs[0]
                    self.run = self.paragraph.add_run()
                    self.run.add_picture(self.folderAddress + "\\" + self.b +
                                         ".png",
                                         width=350000 * 0.71,
                                         height=350000 * 0.49)
            self.document.save(self.folderAddress + "\\" + "singleFolder" +
                               "\\" + self.b + "_" + str(1) + ".docx")

        #print(f'{input_1} and {input_2}')
        self.pageNumber = int(self.page_var.get())
        self.array, self.array2 = [], []
        #print('here')
        for i in range(1, 1 + self.pageNumber):
            self.barcode_Name = self.letter_words_1 + self.letter_words_2 + "00" + str(
                i)
            self.ean = barcode.get(self.Code_128,
                                   self.barcode_Name,
                                   writer=ImageWriter())
            #------------------------
            #print(self.folderAddress+"\\"+self.barcode_Name)
            self.textBox.insert(
                1.0, self.folderAddress + "\\" + self.barcode_Name + "\n")
            self.filename = self.ean.save(
                self.folderAddress + "\\" + self.barcode_Name
            )  #saves to [MG001.png,MG002.png...MG00(pageNumber).png]
            self.array.append(self.folderAddress + "\\" + self.barcode_Name +
                              ".png")
            self.array2.append(self.barcode_Name)

        makeFolder(self)
        for a, b in zip(self.array, self.array2):
            self.b = b
            #self.putIntoDocumentFiles=putIntoDocumentFiles(self,b)
            #self.putIntoDocumentFiles(self,b)
            self.fasterSolution = fasterSolution(self, self.b)
            fasterSolution(self, self.b)
            self.textBox.insert(
                1.0, "Done:" + self.folderAddress + "\\" + self.directoryName +
                "\\" + self.b + "_" + str(1) + ".docx" + "\n")

    def create_thread_version_Two(self, function_name):
        self.run_thread = Thread(target=function_name)
        self.run_thread.setDaemon(True)  # <=== add this line
        self.run_thread.start()
        self.textBox.insert(1.0, str(self.run_thread) + "\n")
        self.textBox.insert(1.0, str(self.run_thread.isAlive()) + "\n")

        #
    def create_thread(self):
        self.run_thread = Thread(target=self.action)
        self.run_thread.setDaemon(True)  # <=== add this line
        self.run_thread.start()
        #-------------------
        #print(self.run_thread)
        #print('createThread():',self.run_thread.isAlive())
        self.textBox.insert(1.0, str(self.run_thread) + "\n")
        self.textBox.insert(1.0, str(self.run_thread.isAlive()) + "\n")
        #-------------------

    def create_thread_two(self):
        self.run_thread = Thread(target=self.download_youtube_video)
        self.run_thread.setDaemon(True)  # <=== add this line
        self.run_thread.start()

        self.textBox.insert(1.0, str(self.run_thread) + "\n")
        self.textBox.insert(1.0, str(self.run_thread.isAlive()) + "\n")

    def create_thread_three(self):
        self.run_thread = Thread(target=self.download_youtube_video_with_audio)
        self.run_thread.setDaemon(True)  # <=== add this line
        self.run_thread.start()

        self.textBox.insert(1.0, str(self.run_thread) + "\n")
        self.textBox.insert(1.0, str(self.run_thread.isAlive()) + "\n")

    #function sets title to Untitled and deletes everything from textBox
    def new_file(self, event=None):
        self.win.title("Untitled")
        global file_name
        file_name = None
        self.textBox.delete(1.0, END)
        #on_content_changed()

    #function opens file from devices, sets title to opened file name and insert text into textBox
    def open_file(self, event=None):
        input_file_name = tkinter.filedialog.askopenfilename(
            defaultextension=".txt",
            filetypes=[("All Files", "*.*"), ("Text Documents", "*.txt")])
        if input_file_name:
            global file_name
            file_name = input_file_name
            self.win.title('{} - {}'.format(os.path.basename(file_name),
                                            'GUI'))
            self.textBox.delete(1.0, END)
            with open(file_name) as _file:
                self.textBox.insert(1.0, _file.read())
            #on_content_changed()

    #function writes text from textBox into file_name
    def write_to_file(self, file_name):
        try:
            content = self.textBox.get(1.0, 'end')
            with open(file_name, 'w') as the_file:
                the_file.write(content)
        except IOError:
            tkinter.messagebox.showwarning("Save", "Could not save the file.")

#function takes file name as input and then runs subfunctions and also sets title to saved file path

    def save_as(self, event=None):
        input_file_name = tkinter.filedialog.asksaveasfilename(
            defaultextension=".txt",
            filetypes=[("All Files", "*.*"), ("Text Documents", "*.txt")])
        if input_file_name:
            #global self.file_name
            self.file_name = input_file_name
            self.write_to_file(self.file_name)
            self.win.title('{} - {}'.format(os.path.basename(self.file_name),
                                            'GUI'))
        return "break"

    #function saves file_name if not exists as save as function, else write_to_file function
    def save(self, event=None):
        #global self.file_name

        if not self.file_name:
            self.save_as()
        else:
            self.write_to_file(self.file_name)
        return "break"

    def exit_editor(self, event=None):
        if tkinter.messagebox.askokcancel("Quit?", "Really quit?"):
            self.win.destroy()

    def undo(self):
        self.textBox.event_generate("<<Undo>>")
        #on_content_changed()
        return "break"

    def redo(self, event=None):
        self.textBox.event_generate("<<Redo>>")
        #on_content_changed()
        return 'break'

    #function finds text that matches the pattern inserted into the entry widget and then does a search by
    #giving it to another function named search_output
    def find_text(self, event=None):
        self.search_toplevel = Toplevel(self.win)
        self.search_toplevel.title('Find Text')
        self.search_toplevel.transient(self.win)

        Label(self.search_toplevel, text="Find All:").grid(row=0,
                                                           column=0,
                                                           sticky='e')

        self.search_entry_widget = Entry(self.search_toplevel, width=25)
        self.search_entry_widget.grid(row=0,
                                      column=1,
                                      padx=2,
                                      pady=2,
                                      sticky='we')
        self.search_entry_widget.focus_set()

        self.ignore_case_value = IntVar()
        Checkbutton(self.search_toplevel,
                    text='Ignore Case',
                    variable=self.ignore_case_value).grid(row=1,
                                                          column=1,
                                                          sticky='e',
                                                          padx=2,
                                                          pady=2)
        Button(self.search_toplevel,
               text="Find All",
               underline=0,
               command=lambda: self.search_output(
                   self.search_entry_widget.get(), self.ignore_case_value.get(
                   ), self.textBox, self.search_toplevel, self.
                   search_entry_widget)).grid(row=0,
                                              column=2,
                                              sticky='e' + 'w',
                                              padx=2,
                                              pady=2)

    #function searches for a needle in a haystack accordingly to search custom function of textBox
    def search_output(self, needle, if_ignore_case, content_text,
                      search_toplevel, search_box):
        self.textBox.tag_remove('match', '1.0', END)
        matches_found = 0
        if needle:
            start_pos = '1.0'
            while True:
                start_pos = self.textBox.search(needle,
                                                start_pos,
                                                nocase=if_ignore_case,
                                                stopindex=END)
                if not start_pos:
                    break
                end_pos = '{}+{}c'.format(start_pos, len(needle))
                self.textBox.tag_add('match', start_pos, end_pos)
                matches_found += 1
                start_pos = end_pos
            self.textBox.tag_config('match',
                                    foreground='red',
                                    background='yellow')
        search_box.focus_set()
        search_toplevel.title('{} matches found'.format(matches_found))

    #function creates menubar with submenus as file menubar and edit menubar correspondingly
    def create_menubar(self):
        self.new_file_icon = PhotoImage(file='icons/new_file.gif')
        self.open_file_icon = PhotoImage(file='icons/open_file.gif')
        self.save_file_icon = PhotoImage(file='icons/save.gif')
        self.cut_icon = PhotoImage(file='icons/cut.gif')
        self.copy_icon = PhotoImage(file='icons/copy.gif')
        self.paste_icon = PhotoImage(file='icons/paste.gif')
        self.undo_icon = PhotoImage(file='icons/undo.gif')
        self.redo_icon = PhotoImage(file='icons/redo.gif')

        self.menu_bar = Menu(self.win)
        self.file_menu = Menu(self.menu_bar, tearoff=0)
        self.file_menu.add_command(label='New',
                                   accelerator='Ctrl+N',
                                   compound='left',
                                   image=self.new_file_icon,
                                   underline=0,
                                   command=self.new_file)

        self.file_menu.add_command(label='Open',
                                   accelerator='Ctrl+O',
                                   compound='left',
                                   image=self.open_file_icon,
                                   underline=0,
                                   command=self.open_file)
        self.file_menu.add_command(label='Save',
                                   accelerator='Ctrl+S',
                                   compound='left',
                                   image=self.save_file_icon,
                                   underline=0,
                                   command=self.save)
        self.file_menu.add_command(label='Save as',
                                   accelerator='Shift+Ctrl+S',
                                   command=self.save_as)
        self.file_menu.add_separator()
        self.file_menu.add_command(label='Exit',
                                   accelerator='Alt+F4',
                                   command=self.exit_editor)
        self.menu_bar.add_cascade(label='File', menu=self.file_menu)

        self.edit_menu = Menu(self.menu_bar, tearoff=0)
        self.edit_menu.add_command(label='Undo',
                                   accelerator='Ctrl+Z',
                                   compound='left',
                                   image=self.undo_icon,
                                   command=self.undo)
        self.edit_menu.add_command(label='Redo',
                                   accelerator='Ctrl+Y',
                                   compound='left',
                                   image=self.redo_icon,
                                   command=self.redo)
        self.edit_menu.add_separator()
        self.edit_menu.add_command(label='Find',
                                   underline=0,
                                   accelerator='Ctrl+F',
                                   command=self.find_text)
        self.menu_bar.add_cascade(label='Edit', menu=self.edit_menu)

        self.win.config(menu=self.menu_bar)

    #function create widgets like Label, Combobox, Entry and Button
    def create_widget(self):
        #made a label at zero row and zero column to select input between A-Z at the corresponding combobox
        self.gender_label = ttk.Label(self.win, text='Select input 1 : ')
        self.gender_label.grid(row=0, column=0, sticky=tk.W)

        self.gender_var = tk.StringVar()
        self.gender_combobox = ttk.Combobox(self.win,
                                            width=14,
                                            textvariable=self.gender_var,
                                            state='readonly')
        self.gender_combobox['values'] = ('A', 'B', 'C', 'D', 'E', 'F', 'G',
                                          'H', 'I', 'J', 'K', 'L', 'M', 'N',
                                          'O', 'P', 'Q', 'R', 'S', 'T', 'U',
                                          'W', 'X', 'Y', 'Z')
        self.gender_combobox.current(0)
        self.gender_combobox.grid(row=0, column=1)

        #made a label at first row and zero column to select input between A-Z at the corresponding combobox
        self.gender_label_2 = ttk.Label(self.win, text='Select input 2 : ')
        self.gender_label_2.grid(row=1, column=0, sticky=tk.W)

        self.gender_var_2 = tk.StringVar()
        self.gender_combobox_2 = ttk.Combobox(self.win,
                                              width=14,
                                              textvariable=self.gender_var_2,
                                              state='readonly')
        self.gender_combobox_2['values'] = ('A', 'B', 'C', 'D', 'E', 'F', 'G',
                                            'H', 'I', 'J', 'K', 'L', 'M', 'N',
                                            'O', 'P', 'Q', 'R', 'S', 'T', 'U',
                                            'W', 'X', 'Y', 'Z')
        self.gender_combobox_2.current(0)
        self.gender_combobox_2.grid(row=1, column=1)

        #made a label at second row and zero column to take corresponding entry as input between 1-inf
        self.page_label = ttk.Label(self.win,
                                    text='Until page number starting from 1: ')
        self.page_label.grid(row=2, column=0, sticky=tk.W)

        self.page_var = tk.IntVar()
        self.page_number = Entry(bd=5, textvariable=self.page_var)
        self.page_number.grid(row=2, column=1, sticky=tk.W)

        #submit button is attached to function action here which is inside create_thread function
        self.submit_button = ttk.Button(self.win,
                                        text='print Barcodes',
                                        command=self.create_thread)
        self.submit_button.grid(row=4, column=0)

        #made a label at fifth row and zero column that takes youtube url as input
        self.youtube_label = ttk.Label(self.win, text='Give youtube url : ')
        self.youtube_label.grid(row=5, column=0, sticky=tk.W)

        self.youtube_url_var = tk.StringVar()
        self.youtube_url = Entry(bd=5, textvariable=self.youtube_url_var)
        self.youtube_url.grid(row=5, column=1, sticky=tk.W)

        self.youtube_var = tk.StringVar()
        self.youtube_combobox = ttk.Combobox(self.win,
                                             width=14,
                                             textvariable=self.youtube_var,
                                             state='readonly')
        self.youtube_combobox['values'] = ("720p", "480p", "360p", "240p",
                                           "144p")
        self.youtube_combobox.current(0)
        self.youtube_combobox.grid(row=5, column=2)

        #made a label at fifth row and zero column that takes youtube url with or without audio as input
        self.youtube_label_2 = ttk.Label(
            self.win, text='Prefer it with audio or silence : ')
        self.youtube_label_2.grid(row=5, column=3, sticky=tk.W)

        self.youtube_audio_var = tk.BooleanVar()
        self.youtube_combobox_2 = ttk.Combobox(
            self.win,
            width=14,
            textvariable=self.youtube_audio_var,
            state='readonly')
        self.youtube_combobox_2['values'] = (True, False)
        self.youtube_combobox_2.current(0)
        self.youtube_combobox_2.grid(row=5, column=4)

        #youtube button is attached to function download_youtube_video here which is inside create_thread_2 function
        self.youtube_button = ttk.Button(
            self.win,
            text='download youtube video from a url',
            command=self.create_thread_two)
        self.youtube_button.grid(row=6, column=0)

        #WRONG WAY OF DOING IT
        #self.youtube_button_1=ttk.Button(self.win,text='download youtube video from a url with audio or not',command=self.create_thread_version_Two(self.download_youtube_video_with_audio))
        self.youtube_button_1 = ttk.Button(
            self.win,
            text='download youtube video from a url with audio or not',
            command=self.create_thread_three)
        self.youtube_button_1.grid(row=6, column=2)

        self.textBox = ScrolledText(self.win, borderwidth=3, relief="sunken")
        self.textBox.grid(column=0, row=7, columnspan=6, rowspan=1, sticky='W')

    def __init__(self, interval=1):
        """ Constructor
            :type interval: int
            :param interval: Check interval, in seconds
            """
        self.stop = 0
        self.interval = interval
        self.win = tk.Tk()
        self.win.geometry('800x500')
        self.win.title('GUI')
        self.directoryName = "singleFolder"
        self.folderAddress = os.getcwd()
        #self.start_thread=start_thread
        #self.stopped=stopped
        self.create_widget()
        self.file_name = None
        self.create_menubar()
        self.win.mainloop()
コード例 #10
0
def make_docx(infile):

  #generate facture number and filename for saving
  facture_n, outfile = create_facture_n()

  #step 1: get info from text
  commande_n, reference_n, total_ht, total_tva, total_ttc, tasks, prices = get_contents(infile)
  

  #step 2b: append the reference number to the end of the pdf file
  move_pdf(infile, reference_n)

  #step 3: make the doc file
  #prepare shadings for 2 final table cells
  shading_1 = parse_xml(r'<w:shd {} w:fill="#99ccff"/>'.format(nsdecls('w')))
  shading_2 = parse_xml(r'<w:shd {} w:fill="#99ccff"/>'.format(nsdecls('w')))

  newdoc = Document()

  #Title info
  p1 = newdoc.add_paragraph()
  p1.add_run('Tom Viart').bold = True
  p1.add_run('''
132 rue du Chemin Vert
75011 PARIS
Tél : 06 47 59 86 17''')
  p1.add_run('''
Identifiant SIRET : 75105892600021
N° TVA : FR 68 751058926''').bold = True

  p2 = newdoc.add_paragraph('À l’attention d’')
  p2.add_run('ALTO').bold = True
  p2.add_run('''
99, rue du Faubourg Saint Martin
75010 PARIS
  ''')
  p2.alignment = WD_ALIGN_PARAGRAPH.RIGHT

  today = datetime.datetime.today().strftime('%d/%m/%Y')
  p3 = newdoc.add_paragraph()
  p3.add_run('FACTURE %d' % facture_n).bold = True
  p3.add_run('''
  En date du %s''' % today)
  p3.alignment = WD_ALIGN_PARAGRAPH.CENTER


  #make the table of prices
  table = newdoc.add_table(rows=5, cols=2)
  table.style = 'Table Grid'
  table.alignment = WD_ALIGN_PARAGRAPH.CENTER


  # format cell widths
  for cell in table.columns[0].cells:
    cell.width = Inches(4.0)
  for cell in table.columns[1].cells:
    cell.width = Inches(0.9)

  a = table.cell(0, 0)
  b = table.cell(0,1)
  A = a.merge(b)

  tt = 'Commande N° %s \nRéférence %s\n' % (commande_n,reference_n)
  A2 = A.add_paragraph(tt)
  A2.alignment = WD_ALIGN_PARAGRAPH.CENTER

  c = table.cell(1,0)
  c.text = tasks
  d = table.cell(1,1)
  d.text = prices
  d.paragraphs[0].paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
  e = table.cell(2,0)
  e.text = "Total HT"
  e.paragraphs[0].paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
  e2 = table.cell(2,1)
  e2.text = total_ht
  e2.paragraphs[0].paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
  f = table.cell(3,0)
  f.text = "TVA 20 %"
  f.paragraphs[0].paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
  f2 = table.cell(3,1)
  f2.text = total_tva
  f2.paragraphs[0].paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
  g = table.cell(4,0)
  g.text = "Total TTC"
  g.paragraphs[0].paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
  g._tc.get_or_add_tcPr().append(shading_1)
  g2 = table.cell(4,1)
  g2.text = total_ttc
  g2.paragraphs[0].paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
  g2._tc.get_or_add_tcPr().append(shading_2)




  ### End of document -- does not change
  newdoc.add_paragraph('''\n\nValeur en votre aimable règlement à réception (RIB ci-joint)
  ''')
  newdoc.add_paragraph('''\nRELEVE D’IDENTITE BANCAIRE''')

  table2 = newdoc.add_table(rows=2, cols=4)
  table2.style = 'Table Grid'

  a = table2.cell(0,0)
  a.text = "Banque"
  a = table2.cell(0,1)
  a.text = "Guichet"
  a = table2.cell(0,2)
  a.text = "Numéro de compte"
  a = table2.cell(0,3)
  a.text = "Clé RIB"

  b = table2.cell(1,0)
  b.text = "10278"
  b = table2.cell(1,1)
  b.text = "06041"
  b = table2.cell(1,2)
  b.text = "00020864601"
  b = table2.cell(1,3)
  b.text = "54"


  newdoc.add_paragraph('''
  IDENTIFICATION INTERNATIONALE''')

  table3 = newdoc.add_table(rows=1, cols=1)
  table3.style = 'Table Grid'
  a = table3.cell(0,0)
  a.text = '''IBAN : FR76 1027 8060 4100 0208 6460 154
BIC : CMCIFR2A'''


  newdoc.save(outfile)
  out_location = os.path.abspath(os.path.join(os.getcwd(), outfile))

  # Update the facture xls document using update facture() function
  try:
    update_facture(facture_n, reference_n, total_ht)
    print("   Created file: ",outfile)
  except:
    print("!! Error making excel file for {}".format(infile))
    #print("\n".join([commande_n, reference_n, total_ht, total_tva, total_ttc, tasks, prices]))
    

  #open DOC file
  open_file_for_tom(r'C:\Program Files\Microsoft Office\root\Office16\WINWORD.EXE', out_location)
  
  #create a warning message if not all values were found
  if '' in [commande_n, reference_n, total_ht, total_tva, total_ttc, tasks, prices]:
    from easygui import msgbox
    msgbox(msg='Error: program did not correctly find all values', title='Error', ok_button='OK', image=None, root=None)
    errors = pd.DataFrame([commande_n, reference_n, total_ht, total_tva, total_ttc, tasks, prices],columns = ['commande_n', 'reference_n', 'total_ht', 'total_tva', 'total_ttc', 'tasks', 'prices'])
    errors.to_csv('errors.csv',index=False)
コード例 #11
0
ファイル: chart.py プロジェクト: joydesigner/csdn-python
plt.savefig(imgname)

# generate word
document = Document()
document.add_heading('Data analysis Report', level=0)
first_student = students.iloc[0, :]['Name']
first_score = students.iloc[0, :]['Score']

p = document.add_paragraph('The highest score is student ')
p.add_run(str(first_student)).bold = True
p.add_run(', score is ')
p.add_run(str(first_score)).bold = True

p1 = document.add_paragraph(
    f'Totally {len(students.Name)} students attended the test, the summary of the testing is:'
)

table = document.add_table(rows=len(students.Name) + 1, cols=2)
table.style = 'LightShading-Accent1'

table.cell(0, 0).text = 'Student Name'
table.cell(0, 1).text = 'Student Score'

for i, (index, row) in enumerate(students.iterrows()):
    table.cell(i + 1, 0).text = str(row['Name'])
    table.cell(i + 1, 1).text = str(row['Score'])

document.add_picture(imgname)
document.save('Students.docx')
print('Done!!')
コード例 #12
0
def merger(docs=[]):
    list_of_data = []
    list_of_names = []
    for z in docs:
        name = z.split(".")
        na = name[0]
        k = na.split("static/merge/")
        na = k[1]
        list_of_names.append(na)
    for x in docs:
        list_of_data.append(read_table(x))


##    print(list_of_names)
##    print(list_of_data)
##    return(0)

    documentx = Document("static/merge/start.docx")
    documentx.add_page_break()
    y = 0
    #print(list_of_data[0][0])
    x = 0
    op = list_of_data
    list_of_comments = []
    k = 0
    m = 0
    while True:
        templist = []
        try:
            for y in op[m]:
                templist.append(y['comments'])
            list_of_comments.append(templist)
        except Exception as e:
            break
        m += 1

    list_of_titles = []
    k = 0
    for x in op:
        templist = []
        for y in op[0]:
            templist.append(y['title'])
        list_of_titles.append(templist)
        k += 1
        list_of_titles = list_of_titles[0]
        break
    post = 0
    for data in list_of_data:
        com = 0
        for z in data[0]:
            xc = len(data[0])
            documentx.add_heading(list_of_titles[post], level=1)
            post += 1
            y = len(list_of_data)
            x = 0
            #print(list_of_comments)
            while x < len(list_of_data):
                print(x, com)
                head = list_of_names[x] + '\n'
                p = documentx.add_paragraph('\n')
                p.add_run(head).bold = True
                p.add_run(list_of_comments[x][com])
                x += 1
            com += 1
            documentx.add_page_break()
        break
    documentx.save('static/merge/report.docx')
コード例 #13
0
for item in data:
    print(globalCounter)
    cells = targetTable.add_row().cells
    cells[0].text = str(globalCounter)
    cells[1].text = item[1][1]
    cells[2].text = item[2][1]
    cells[3].text = item[3][1]
    cells[4].text = item[4][1]
    cells[5].text = item[5][1]
    cells[6].text = item[6][1]
    cells[7].text = item[7][1]
    cells[8].text = item[8][1]
    cells[9].text = item[9][1]
    globalCounter = globalCounter + 1

targetDoc.save('C:\\Users\\KyleRid\\Desktop\\py\\source\\target2.docx')

#copy
# header = ()
# data = []
# counter = 0
# keys = None
# for i, row in enumerate(table.rows):
#     text = (cell.text for cell in row.cells)
#     if i == 0:
#         keys = tuple(text)
#         continue
#     counter = counter + 1
#     row_data = dict(zip(keys, text))
#     if not header and counter == 1:
#         header = row_data
コード例 #14
0
# -*- coding: utf-8 -*-
from docx.api import Document


def delete_paragraph(paragraph):
    p = paragraph._element
    p.getparent().remove(p)
    p._p = p._element = None


# Load the first table from your document. In your example file,
# there is only one table, so I just grab the first one.
document = Document('10.docx')

story = document.tables[1]

# Data will be a list of rows represented as dictionaries
# containing each row's data.
data = []

keys = None
for i, row in enumerate(story.rows):
    cur_cell = row.cells[3]
    for paragraph in cur_cell.paragraphs:
        for run in paragraph.runs:
            if not run.italic:
                paragraph.clear()
                paragraph.style = None
                break
document.save('../' + unicode('серия_10', 'utf-8') + '.docx')
コード例 #15
0
class ThreadingExample(object):
    """ Threading example class
    The run() method will be started and it will run in the background
    until the application exits.
    """

    ## function makes a folder named singleFolder if doesn't exists and put corresponding documents of barcodes
    ## code_128 barcodes are taken as input from two label above and then given as input to another function
    ## sub functions are defined as putIntoDocumentFiles and a faster version of it
    def action(self):
        while True:
            print("hello")
            if self.stop == 1: break
        self.progress = Progressbar(self.win,
                                    orient="horizontal",
                                    length=300,
                                    mode='determinate')
        self.progress.grid(row=6)
        self.progress["maximum"] = 100
        self.start_time = time.time()
        #Starting progress bar here
        self.progress.start()

        self.directoryName = "singleFolder"

        self.folderAddress = os.getcwd()
        self.progress['value'] = time.time() - self.start_time
        self.progress.update()

        def makeFolder(self):
            try:
                os.mkdir(self.folderAddress + "\\" + self.directoryName)
            except FileExistsError:
                pass

        self.makeFolder = makeFolder(self)

        self.Code_128 = "code128"
        self.letter_words_1 = self.gender_var.get()
        self.letter_words_2 = self.gender_var_2.get()
        self.progress['value'] = time.time() - self.start_time
        self.progress.update()

        def fasterSolution(self, b):
            self.progress['value'] = time.time() - self.start_time
            self.progress.update()
            self.document = Document()
            self.COLUMNS = 4
            self.ROWS = 1000
            self.table = self.document.add_table(rows=self.ROWS,
                                                 cols=self.COLUMNS)
            self.table_cells = self.table._cells
            for i in range(self.ROWS):
                self.row_cells = self.table_cells[i * self.COLUMNS:(i + 1) *
                                                  self.COLUMNS]
                for cell in self.row_cells:
                    self.paragraph = cell.paragraphs[0]
                    self.run = self.paragraph.add_run()
                    self.run.add_picture(self.folderAddress + "\\" + self.b +
                                         ".png",
                                         width=350000 * 0.71,
                                         height=350000 * 0.49)
            self.progress['value'] = time.time() - self.start_time
            self.progress.update()
            self.document.save(self.folderAddress + "\\" + "singleFolder" +
                               "\\" + self.b + "_" + str(1) + ".docx")
            self.progress['value'] = time.time() - self.start_time
            self.progress.update()

        """def putIntoDocumentFiles(self,b):
            self.document = Document()
            self.table=document.add_table(rows=100,cols=4)#ROWS=25 For 100 barcodes 
            for row in self.table.rows:
                for cell in row.cells:
                    self.paragraph=cell.paragraphs[0]
                    self.run=self.paragraph.add_run()
                    self.run.add_picture(self.folderAddress+"\\"+self.b+".png",width=350000*0.71,height=350000*0.49)#(width,height)=>dimensions(singleTableRow,singleTableColumn) for singlePage
            self.document.save(self.folderAddress+"\\singleFolder"+"\\"+self.b+"_"+"1"+".docx")
            #for i in range(2):
                #document.save(folderAddress+"\\singleFolder"+"\\"+pic+"_"+str(i+1)+".docx")
        """

        #print(f'{input_1} and {input_2}')
        self.pageNumber = int(self.page_var.get())
        self.array, self.array2 = [], []
        #print('here')
        for i in range(1, 1 + self.pageNumber):
            self.progress['value'] = time.time() - self.start_time
            self.progress.update()
            self.barcode_Name = self.letter_words_1 + self.letter_words_2 + "00" + str(
                i)
            self.ean = barcode.get(self.Code_128,
                                   self.barcode_Name,
                                   writer=ImageWriter())
            print(self.folderAddress + "\\" + self.barcode_Name)
            self.filename = self.ean.save(
                self.folderAddress + "\\" + self.barcode_Name
            )  #saves to [MG001.png,MG002.png...MG00(pageNumber).png]
            self.array.append(self.folderAddress + "\\" + self.barcode_Name +
                              ".png")
            self.array2.append(self.barcode_Name)

        makeFolder(self)
        for a, b in zip(self.array, self.array2):
            self.b = b
            self.progress['value'] = time.time() - self.start_time
            self.progress.update()

            #self.putIntoDocumentFiles=putIntoDocumentFiles(self,b)
            #self.putIntoDocumentFiles(self,b)

            self.fasterSolution = fasterSolution(self, self.b)
            fasterSolution(self, self.b)
        self.progress['value'] = time.time() - self.start_time
        self.progress.update()
        #Stopping progress bar here
        self.progress.stop()

    def start_thread(self):
        global stop
        self.stop = 0
        t = Thread(target=self.action)
        t.start()

    def stopped(self):
        global stop
        self.stop = 1

    def __init__(self, interval=1):
        """ Constructor
        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.stop = 0
        self.interval = interval
        self.win = tk.Tk()
        self.win.geometry('350x350')
        self.win.title('GUI')
        #self.start_thread=start_thread
        #self.stopped=stopped

        #made a label at zero row and zero column to select input between A-Z at the corresponding combobox
        self.gender_label = ttk.Label(self.win, text='Select input 1 : ')
        self.gender_label.grid(row=0, column=0, sticky=tk.W)

        self.gender_var = tk.StringVar()
        self.gender_combobox = ttk.Combobox(self.win,
                                            width=14,
                                            textvariable=self.gender_var,
                                            state='readonly')
        self.gender_combobox['values'] = ('A', 'B', 'C', 'D', 'E', 'F', 'G',
                                          'H', 'I', 'J', 'K', 'L', 'M', 'N',
                                          'O', 'P', 'Q', 'R', 'S', 'T', 'U',
                                          'W', 'X', 'Y', 'Z')
        self.gender_combobox.current(0)
        self.gender_combobox.grid(row=0, column=1)

        #made a label at first row and zero column to select input between A-Z at the corresponding combobox
        self.gender_label_2 = ttk.Label(self.win, text='Select input 2 : ')
        self.gender_label_2.grid(row=1, column=0, sticky=tk.W)

        self.gender_var_2 = tk.StringVar()
        self.gender_combobox_2 = ttk.Combobox(self.win,
                                              width=14,
                                              textvariable=self.gender_var_2,
                                              state='readonly')
        self.gender_combobox_2['values'] = ('A', 'B', 'C', 'D', 'E', 'F', 'G',
                                            'H', 'I', 'J', 'K', 'L', 'M', 'N',
                                            'O', 'P', 'Q', 'R', 'S', 'T', 'U',
                                            'W', 'X', 'Y', 'Z')
        self.gender_combobox_2.current(0)
        self.gender_combobox_2.grid(row=1, column=1)

        #made a label at second row and zero column to take corresponding entry as input between 1-inf
        self.page_label = ttk.Label(self.win,
                                    text='Until page number starting from 1: ')
        self.page_label.grid(row=2, column=0, sticky=tk.W)

        self.page_var = tk.IntVar()
        self.page_number = Entry(bd=5, textvariable=self.page_var)
        self.page_number.grid(row=2, column=1, sticky=tk.W)

        #self.thread = threading.Thread(name="action",target=self.action)
        #self.thread.daemon = False                         # Daemonize thread
        #thread.start()                                  # Start the execution

        #submit button is attached to function action here
        self.submit_button = ttk.Button(self.win,
                                        text='print Barcodes',
                                        command=self.start_thread)
        self.submit_button.grid(row=4, column=0)
        self.stop_button = ttk.Button(self.win,
                                      text='Stop',
                                      command=self.stopped)
        self.stop_button.grid(row=5, column=0)
        self.win.mainloop()
コード例 #16
0
def main():
  print(forms_dir)
  get_files(forms_dir, forms)
  for dir in templates_dirs:
    get_files(dir, templates)

  #pull values
  for form_dir in forms:
    print(form_dir)
    if form_dir.endswith('.docx'):
      doc = Document(form_dir)
      for table in doc.tables:
        for i, row in enumerate(table.rows):
          check = False
          try:
            check = check_alias(row.cells[0].text)
          except IndexError:
            continue

          if check != False:
            cell_text = row.cells[1].text
            if (check in alias_vals.keys()) and (alias_vals[check] != cell_text):
              if (check in conflicts.keys()) == False:
                conflicts[check] = [row.cells[1].text, alias_vals[check]]
              else:
                conflicts[check].append(row.cells[1].text)

            else:
              alias_vals[check] = cell_text

  #resolve conflicting values
  # for label in conflicts:
  #   print("There's conflicting values for label " + label)
  #   for i, value in enumerate(conflicts[label]):
  #     print(str(i) + ") " + value)
  #   sys.stdout.flush()
  #   s = input("Select which value to use: ")
  #   print(s)
  #   sys.stdout.flush()
  #   alias_vals[label] = conflicts[label][int(s)]

  for label in conflicts:
    popup = tk.Toplevel()
    popup.title("Label value conflict")
    text = Label(popup, text=("There's conflicting values for label " + label))
    text.grid(row=0, column=0)
    for i, value in enumerate(conflicts[label]):
      def on_press():
        popup.destroy()
        alias_vals[label] = conflicts[label][i]
      button = Button(popup, text=value, command=on_press)
      button.grid(row=(i + 1), column=0)
    global app
    app.wait_window(popup)

  #clone values
  for template_dir in templates:
    if template_dir.endswith('.docx') and template_dir.find('~') == -1:
      doc = Document(template_dir)
      clone_values(doc)
      for section in doc.sections:
        clone_values(section.header)
        clone_values(section.footer)
      doc.save(template_dir)
    elif template_dir.endswith('.xlsx'):
      wb = openpyxl.load_workbook(template_dir)
      for sheet_name in wb.sheetnames:
        sheet = wb[sheet_name]
        for row in sheet.iter_rows():
          for cell in row:
            cell_text = cell.value
            if (cell_text != 'None' and cell_text is not None):
              for label in alias_vals:
                val = alias_vals[label]
                if type(label) is str:
                  check = list(
                      find_all(cell_text.strip().lower(), label.strip().lower()))
                  if len(check) > 0:
                    # print(cell_text)
                    if len(check) == 1:
                      if (check[0] == 0 and cell_text.strip().lower() == label.strip().lower()):
                        cell.value = val
                      elif check[0] != 0:
                        cell.value = cell_text[:check[0]] + \
                            val + cell_text[(len(val) + check[0]):]
                    else:
                      last_index = check[len(check) - 1]
                      cell.value = cell_text[:last_index] + \
                          val + cell_text[(len(val) + last_index):]
      wb.save(template_dir)