I need to develop a tool that will be able to check text, I only care about checking words. An Excel sheet will serve as the GUI, or if you have a better idea where to place it, I will be grateful. On the left there is text to be checked, on the right there is text from the pattern/template that is correct. Currently, the program is not immune to noise caused by separators, spaces, enters, tabs, and double spaces. Maybe someone was developing a similar text analyzer. I want him to mark repeated words in green.
PYTHON code:
import argparse
import difflib
import os
import os
import traceback
def read_txt_file(filename):
“””Reads the content of a txt file.”””
with open(filename, 'r', encoding='utf-8-sig') as file:
return file.read()
def compare_texts(text1, text2):
# Split the texts into lines
lines1 = text1.splitlines()
lines2 = text2.splitlines()
# Create a Differ object
d = difflib.Differ()
# Calculate the differences
diff = d.compare(lines1, lines2)
# Print the differences
for line in diff:
print(line)
def main():
parser = argparse.ArgumentParser(description="Compare two texts and find the differences.")
parser.add_argument('file1', type=str, help='Path to the first text file')
parser.add_argument('file2', type=str, help='Path to the second text file')
args = parser.parse_args()
text1 = read_txt_file(args.file1)
text2 = read_txt_file(args.file2)
compare_texts(text1, text2)
if name == “main“:
try:
main()
except Exception as e:
# Construct the full path to PythonError.txt in the same directory as main.py
error_file_path = os.path.join(os.path.dirname(os.path.realpath(file)), “PythonError.txt”)
# Write the error message and traceback to PythonError.txt
with open(error_file_path, "w+") as file:
file.write(f"Exception occurred: {str(e)}n")
file.write(f"Traceback:n{traceback.format_exc()}")
VBA code:
Option Explicit
‘ —————————–
‘ Implementacja Shell + Python script.
‘
‘ Zadziała tylko na Systemie Operacyjnym Windows.
‘ —————————–
Private Const ARKUSZ_WEJŚCIOWY_NAZWA As String = “Arkusz Wejściowy”
Private Const ARKUSZ_PORÓWNYWARKA_NAZWA As String = “Porównywarka”
Private Const MODE = 1 ‘ 1 oznacza, że wszystko będzie wyświetlane, 2 oznacza że tylko zmiany będą wyświetlane.
Public Sub Guzik_click()
Call StworzKomendeDoWezwania
End Sub
Private Sub WrzućZawartośćPlikuDoNowegoTxt(ByRef strZawartość As String, ByRef strNazwa As String)
‘ *** Wrzuca zawartość pliku do txt w kodowaniu UTF-8. TO JEST BARDZO WAŻNE, JEŚLI BĘDZIESZ CHCIAŁ TEGO TYPU SZTUCZKI ROBIĆ W PRZYSZŁOŚCI TO ZAPISZ SOBIE GDZIEŚ TĄ FUNKCJE! ***
Dim fsT As Object
Set fsT = CreateObject("ADODB.Stream")
fsT.Type = 2 'Specify stream type - we want To save text/string data.
fsT.Charset = "utf-8" 'Specify charset For the source text data.
fsT.Open 'Open the stream And write binary data To the object
fsT.WriteText strZawartość
fsT.SaveToFile strNazwa, 2 'Save binary data To disk
End Sub
Private Sub StworzKomendeDoWezwania()
‘ *** Do CMD chcemy podać:
‘ a) Ustal ścieżkę gdzie znajduje się skrypt pythonowski
‘ b) Uruchom venv (środowisko wirtualne)
‘ c) Wywołaj skrypt – przy czym skrypt przyjmuje zawartość 2 plików txt (nie dało się podać bezpośrednio tak długiego i złożonego tekstu)
‘ d) Zczytaj wynik
‘ Dla uproszczenia powiedzmy, że skrypt pythonowski znajduje się w tym samym folderze co Excel.
‘ ***
Dim strKomenda As String
Dim strSciezkaDoSiebie As String
Dim strTekst As String
Dim strZawartość1 As String
Dim strZawartość2 As String
strZawartość1 = WyczyśćZawartość(Worksheets(ARKUSZ_WEJŚCIOWY_NAZWA).Cells(1, 1).Value)
strZawartość2 = WyczyśćZawartość(Worksheets(ARKUSZ_WEJŚCIOWY_NAZWA).Cells(1, 13).Value)
strSciezkaDoSiebie = Left(ThisWorkbook.FullName, InStrRev(ThisWorkbook.FullName, Application.PathSeparator))
Call WrzućZawartośćPlikuDoNowegoTxt(strZawartość1, strSciezkaDoSiebie & "1.txt")
Call WrzućZawartośćPlikuDoNowegoTxt(strZawartość2, strSciezkaDoSiebie & "2.txt")
strKomenda = "cmd.exe /c cd " & Chr(34) & strSciezkaDoSiebie & Chr(34) & " && " & Left(strSciezkaDoSiebie, 1) & ": && "
' Ta linijka wzywa skrypt do wykonania, razem z podanymi ścieżkami.
' chr(34) oznacza " - jest to bardzo użyteczny znak zwłaszcza w tej sytuacji.
strKomenda = strKomenda & "venvScriptsactivate.bat && main.py " & Chr(34) & strSciezkaDoSiebie & "1.txt" & Chr(34) & " " & Chr(34) & strSciezkaDoSiebie & "2.txt" & Chr(34) & " " & MODE
strTekst = WywolajKomendeWCMD(strKomenda)
Call WyplujWynik(strTekst)
' Usuwa pliki stworzone tymczasowo
Call Kill(strSciezkaDoSiebie & "1.txt")
Call Kill(strSciezkaDoSiebie & "2.txt")
End Sub
Private Function WywolajKomendeWCMD(ByVal strKomenda As String) As String
‘ Odpowiada za wywołanie komendy w CMD i zwrócenie wyniku
Dim shell As Object
Dim exec As Object
Dim output As String
Dim inputLine As String
Debug.Print strKomenda
Set shell = CreateObject("WScript.Shell")
Set exec = shell.exec(strKomenda)
' ZZczytuje wynik z CMD
output = ""
Do While Not exec.StdOut.AtEndOfStream
inputLine = exec.StdOut.ReadLine
output = output & inputLine & vbCrLf
Loop
WywolajKomendeWCMD = output
Debug.Print " "
Debug.Print "-------------------------------------------------------------------------------------------"
Debug.Print output
Debug.Print "-------------------------------------------------------------------------------------------"
End Function
Private Sub WyplujWynik(ByRef strText As String)
‘ *** Wrzuca wynik do nowego arkusza przy założeniu – jedna lnijka jeden wiersz. ***
Dim wsArkusz As Worksheet
Dim arrLnijki As Variant
Dim varLnijka As Variant
Dim lngWiersz As Long
Set wsArkusz = Worksheets(ARKUSZ_PORÓWNYWARKA_NAZWA)
With wsArkusz.Range("A1:A10000")
.Value = ""
.Font.Color = vbBlack
End With
arrLnijki = Split(strText, vbCrLf)
lngWiersz = 1
For Each varLnijka In arrLnijki
wsArkusz.Cells(lngWiersz, 1).Value = varLnijka
If Left(varLnijka, 1) = "+" Then
wsArkusz.Cells(lngWiersz, 1).Font.Color = RGB(0, 150, 0) ' Ciemny Zielony powinien być czytelniejszt
ElseIf Left(varLnijka, 1) = "-" Then
wsArkusz.Cells(lngWiersz, 1).Font.Color = RGB(255, 0, 0) ' Czerwony
End If
lngWiersz = lngWiersz + 1
Next varLnijka
wsArkusz.Select
End Sub
Private Function WyczyśćZawartość(ByVal strZawartość As String) As String
‘ *** Czyści zawartość tekstu, jeśli chcesz mieć nic, to wywal wszystko i na ostatniej lnijce wpisz: WyczyśćZawartość = strZawartość ***
strZawartość = Replace(strZawartość, "/*", "")
strZawartość = UsuńZbędneElementyZTekstuWNadmiarze(strZawartość, Chr(10)) ' Entery
strZawartość = UsuńZbędneElementyZTekstuWNadmiarze(strZawartość, Chr(32)) ' Spacje
WyczyśćZawartość = strZawartość
End Function
Private Function UsuńZbędneElementyZTekstuWNadmiarze(ByVal strZawartość As String, ByVal strElement As String) As String
‘ ***
‘ Przechodzi przez tekst. Jeśli znajduje wybrany element, to sprawdza czy kolejne są takie same.
‘ Jeśli tak, to je zamienia na jeden instance rzeczonego elementu.
‘ ***
Dim tymczTekst As String
Dim i As Long
Dim lngLicz As Long
tymczTekst = ""
lngLicz = 0
' Usuwa nadmiarowe elementy.
For i = 1 To Len(strZawartość)
If Mid(strZawartość, i, 1) = strElement Then
lngLicz = lngLicz + 1
Else
lngLicz = 0
End If
If lngLicz <= 1 Then
tymczTekst = tymczTekst & Mid(strZawartość, i, 1)
End If
Next i
UsuńZbędneElementyZTekstuWNadmiarze = tymczTekst
End Function
enter image description here
enter image description here
user26456193 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.