surya3141 / i-Ai

0 stars 0 forks source link

Python #2

Open surya3141 opened 1 month ago

surya3141 commented 1 month ago

To modify the solution so that the Excel file is also kept in the same folder as the Python script and Word file, here’s the updated plan. This change ensures that the Python script automatically looks for the Excel file in the same folder as the Word document and script.

Updated Folder Structure

Folder Layout:

Word file: Document to be checked.

Excel correction file: grammatical_corrections.xlsx.

Python script: grammar_check.py.


Step 1: Python Script (Updated)

This script will:

  1. Automatically locate the Excel file in the same folder as the Word file.

  2. Perform the grammar corrections by comparing the Word file to the Excel file.

  3. Generate a summary report in the same folder as the Word file.

Here's the updated Python script:

import os import sys import docx import openpyxl

Function to load corrections from the Excel file

def load_corrections(excel_path): corrections = {} wb = openpyxl.load_workbook(excel_path) sheet = wb.active for row in sheet.iter_rows(min_row=2, values_only=True): incorrect_word, correct_word = row if incorrect_word and correct_word: corrections[incorrect_word] = correct_word return corrections

Function to apply corrections and generate summary

def apply_corrections(doc_path, corrections, summary_path): doc = docx.Document(doc_path) summary = [] for i, para in enumerate(doc.paragraphs): original_text = para.text modified_text = original_text for incorrect_word, correct_word in corrections.items(): if incorrect_word in original_text: modified_text = modified_text.replace(incorrect_word, correct_word) summary.append(f"Replaced '{incorrect_word}' with '{correct_word}' in Paragraph {i + 1}")

    para.text = modified_text

# Save the modified document
doc.save(doc_path)

# Save the summary of changes
with open(summary_path, 'w') as summary_file:
    for line in summary:
        summary_file.write(line + "\n")

def main():

Get paths from arguments

folder_path = os.path.dirname(os.path.realpath(__file__))  # Automatically find the script's folder
excel_file = os.path.join(folder_path, "grammatical_corrections.xlsx")
word_file = sys.argv[1]  # Pass the Word document file as the argument
summary_file = os.path.join(folder_path, word_file.replace(".docx", "_GrammarCheckSummary.txt"))

# Load corrections from Excel
corrections = load_corrections(excel_file)

# Apply corrections and generate summary
apply_corrections(word_file, corrections, summary_file)

if name == "main": main()

How This Works:

folder_path: Automatically identifies the folder where the Python script is stored.

excel_file: Assumes the grammatical_corrections.xlsx file is located in the same folder as the Python script.

word_file: The Word document path is provided as an argument when running the script.

summary_file: The generated summary file will be saved in the same folder as the Word document and Python script.


Step 2: VBA Macro (Updated)

The VBA macro will now call the Python script and automatically detect the Word document being edited. It assumes the Excel file is in the same folder as the Word document.

Updated VBA Macro:

Sub RunGrammarCheck() Dim folderPath As String Dim pythonScriptPath As String Dim wordFilePath As String Dim shellObj As Object Dim result As Long

' Set the path to the folder and Python script
folderPath = ThisDocument.Path ' Use the folder where the Word file is stored
pythonScriptPath = folderPath & "\grammar_check.py"
wordFilePath = ThisDocument.FullName ' Path to the current Word document

' Ensure the Python script exists
If Dir(pythonScriptPath) = "" Then
    MsgBox "Python script not found: " & pythonScriptPath
    Exit Sub
End If

' Create a Shell object to run the Python script
Set shellObj = CreateObject("WScript.Shell")

' Run the Python script and pass the Word document path
result = shellObj.Run("python """ & pythonScriptPath & """ """ & wordFilePath & """", 0, True)

' Check result and notify the user
If result = 0 Then
    MsgBox "Grammar check completed. Summary saved in the same folder."
Else
    MsgBox "Error running grammar check."
End If

End Sub

Explanation:

folderPath: Automatically sets the folder where the Word file (and the Python script) is located.

pythonScriptPath: Refers to the Python script in the same folder.

wordFilePath: Refers to the Word document currently open in Word.

shellObj: Calls the Python script and passes the Word document as a command-line argument.


Step 3: Running the Solution

  1. Folder Setup:

Ensure the Word document, Python script (grammar_check.py), and Excel correction file (grammatical_corrections.xlsx) are in the same folder.

  1. Run the Macro:

Open the Word document.

Go to Developer Tab > Macros and run the RunGrammarCheck macro.

The Python script will execute, corrections will be applied, and a summary file will be generated in the same folder.


Step 4: Summary Text File Example

After running the macro, the Python script will generate a summary text file with the changes made, stored in the same folder as the Word document:

Grammar Check Summary for: Document.docx

Replaced 'teh' with 'the' in Paragraph 3 Replaced 'recieve' with 'receive' in Paragraph 5 Replaced 'adress' with 'address' in Paragraph 12


Step 5: Conclusion

This approach allows users to simply place the Word document, Python script, and Excel correction file in the same folder. By running the VBA macro from Word, the Python script will handle the grammar check and corrections based on the Excel file. The results will be stored in a summary text file in the same folder, making it easy for users to review the changes made.

surya3141 commented 1 month ago

Sub RunGrammarCheck() Dim pythonPath As String Dim scriptPath As String Dim excelPath As String Dim wordFilePath As String Dim command As String Dim result As Integer

' Define the path to the Python executable
pythonPath = "C:\Path\To\Python\python.exe"  ' Update this to your Python executable path

' Define the path to the Python script (stored in the shared folder)
scriptPath = "C:\Path\To\CommonFolder\grammar_check.py"  ' Update to the correct path

' Define the path to the Excel file (stored in the shared folder)
excelPath = "C:\Path\To\CommonFolder\grammatical_corrections.xlsx"  ' Update to the correct path

' Get the full path of the current Word document
wordFilePath = ThisDocument.FullName

' Build the command to run the Python script with the Word document and Excel file as arguments
command = pythonPath & " """ & scriptPath & """ """ & wordFilePath & """ """ & excelPath & """"

' Execute the Python script
result = Shell(command, vbNormalFocus)

If result = 0 Then
    MsgBox "Grammar check completed. Please check the summary file in the document folder."
Else
    MsgBox "Error during grammar check."
End If

End Sub

Hesham3182 commented 1 month ago

from kivy.app import App from kivy.uix.gridlayout import GridLayout from kivy.uix.button import Button from kivy.uix.textinput import TextInput

class CalculatorApp(App): def build(self): self.operators = ['+', '-', '*', '/'] self.last_was_operator = None self.last_button = None self.result = TextInput(font_size=32, readonly=True, halign="right", multiline=False)

    layout = GridLayout(cols=4, spacing=10, padding=10)

    layout.add_widget(self.result)

    buttons = [
        '7', '8', '9', '/',
        '4', '5', '6', '*',
        '1', '2', '3', '-',
        '.', '0', '=', '+'
    ]

    for button in buttons:
        layout.add_widget(Button(text=button, on_press=self.on_button_press))

    layout.add_widget(Button(text='C', on_press=self.clear))

    return layout

def on_button_press(self, instance):
    current = self.result.text
    button_text = instance.text

    if button_text == 'C':
        self.result.text = ''
    elif button_text == '=':
        try:
            self.result.text = str(eval(self.result.text))
        except Exception:
            self.result.text = 'Error'
    else:
        if current and (self.last_was_operator and button_text in self.operators):
            return
        elif current == '' and button_text in self.operators:
            return
        else:
            self.result.text += button_text
    self.last_was_operator = button_text in self.operators
    self.last_button = button_text

def clear(self, instance):
    self.result.text = ''

if name == 'main': CalculatorApp().run()