PyQt5 - Display lines from txt file into multiple QTextEdit's - qt

I'm new in pyqt5 and I'm working on a gui that runs tasks from a txt file (each line is a task) and I have 8 QTextEdit's that i already created ,i want after clicking the "execute all tasks" button to display each line into a QTextEdit (for example the first line will be shown in the first QTextEdit, the second line in the second QTextEdit ..., but the ninth line will be displayed in the first QTextEdit , the tenth line in the second QTextEdit ...) and keep looping thru my eight QTextEdit's.
Let's suppose i have a file with 10 lines :
hello1
hello2
hello3
hello4
hello5
hello6
hello7
hello8
hello9
hello10
here is the result i'm trying to reach :
res1
res2
Please check my form
I tried this but my when i click the button " execute all tasks " the form crashes returning this message :
clearzsh: killed python3 main.py
class Task(QDialog):
def __init__(self):
super(Task, self).__init__()
loadUi("task.ui", self)
self.exit.clicked.connect(self.taskscreen)
self.all_b.clicked.connect(self.execute_all)
def taskscreen(self) :
login = MainScreen()
widget.addWidget(login)
widget.setCurrentIndex(widget.currentIndex()+1)
widget.setFixedHeight(620)
widget.setFixedWidth(1080)
def execute_all(self) :
all_textedit = []
t1 = QTextEdit(readOnly=True)
t2 = QTextEdit(readOnly=True)
t3 = QTextEdit(readOnly=True)
t4 = QTextEdit(readOnly=True)
t5 = QTextEdit(readOnly=True)
t6 = QTextEdit(readOnly=True)
t7 = QTextEdit(readOnly=True)
t8 = QTextEdit(readOnly=True)
w = [t1,t2,t3,t4,t5,t6,t7,t8]
while not w in all_textedit :
if isinstance(w, QTextEdit):
all_textedit.append(w)
w = w.nextInFocusChain()
with open("taches.txt") as file :
lines = file.readlines()
it = itertools.chain(w)
for line in lines :
all_textedit = next(it)
all_textedit.append(line)
app = QApplication(sys.argv)
widget = QStackedWidget()
task = Task()
widget.addWidget(task)
widget.setFixedHeight(600)
widget.setFixedWidth(1024)
widget.show()
try :
sys.exit(app.exec_())
except :
print("bye")
Thanks for your support !

Related

Tkinter create RadioButtons from dictionary issue

Here is my problem: I've made a tkinter program which calculate the cost of a creation my wife make. She sews accessories. So far my program is working pretty well. I search in a JSON file if this fabric already exist in some kind of catalogue.
When my catalogue have the same fabric name, I want to make a popup window with radiobutton. By checking the correct radiobutton I chose the correct fabric. So I've extracted the dictionary of same fabric names, when I type the fabric name entry and then click on enter, it sends the dictionnary to the popup window which creates radiobutton in a for loop.
The problem comes here, my radiobutton are correctly made but impossible to get there state nor which button is checked...
First, here's the dictionary :
{"Tissu 1": {"Type": "Tissu", "Matière": "coton", "Prix du coupon": "8",
"Laise du coupon (cm)": "150",
"Prix au mètre (€)": 8.0,
"Fournisseur": "lol"},
"Tissu 2": {"Type": "Tissu", "Matière": "molleton", "Prix du coupon": "10",
"Laise du coupon (cm)": "150",
"Prix au mètre (€)": 10.0,
"Fournisseur": "lol"},
"Tissu 3": {"Type": "Tissu", "Matière": "coton", "Prix du coupon": "12",
"Laise du coupon (cm)": "150",
"Prix au mètre (€)": 12.0,
"Fournisseur": "mol"}}
Here's my code:
First there is the main class:
class ProgramCalcul(tk.Tk):
def __init__(self, *args, **kwargs):
self.frames = {}
for F in (StartPage, CalculTissuPage, CalculMercPage):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row = 0, column = 0, sticky = "nsew")
self.show_frameSP(StartPage)
def show_frameSP(self, cont):
frame = self.frames[cont]
frame.tkraise()
Then I have a class for each other calcul page
Here is the fabric calcul page (I've removed some entries and other widgets for legibility and because they work fine):
class CalculTissuPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
tissuType = tk.StringVar()
TissuNameEntry = tk.Entry(self, textvariable = tissuType, width = 50)
TissuNameEntry.grid(row = 2, padx = 20, pady = 5, sticky = "ew")
def keyPress(arg):
checkCatalogueTissu(TissuNameEntry.get())
TissuNameEntry.bind('<Return>', keyPress)
def checkCatalogueTissu(txt):
tmpDict = {}
with open("catalogue tissu.json") as json_file:
data = json.load(json_file)
dictLen = len(data)
for i in range(1, dictLen+1):
if "Tissu {}".format(i) not in data:
pass
else:
if data["Tissu {}".format(i)]["Matière"] == txt:
tmpDict["Tissu {}".format(i)] = data["Tissu {}".format(i)]
popupRadio(tmpDict)
def setText(txtPrix, txtFournisseur, txtLaise, txtLong):
couponPrixEntry.delete(0,tk.END)
couponPrixEntry.insert(0,txtPrix)
fournisseurEntry.delete(0, tk.END)
fournisseurEntry.insert(0, txtFournisseur)
laiseDimEntry.delete(0, tk.END)
laiseDimEntry.insert(0, txtLaise)
longCouponEntry.delete(0,tk.END)
longCouponEntry.insert(0,txtLong)
And finally the function which create the popup in which appear the radiobuttons:
def popupRadio(tmpDict):
popup = tk.Toplevel()
popup.wm_title("!")
popupVar = tk.IntVar()
def checkState(popupVar):
print(popupVar.get())
for (key, val) in tmpDict.items():
tk.Radiobutton(popup, text = key, variable = popupVar, value = val, command = checkState(popupVar)).grid()
print(key, popupVar.get())
chk = ttk.Button(popup, text = "Select this", command = checkState(popupVar))
chk.grid()
popup.mainloop()
When I run it, the checkState() method seems to run automatically and then the chk button doesn't do anything... I can check the radiobuttons but nothing happens (even if I pass the command=chechState in the radiobutton settings. I want to get which button is checked to use this value in my setText() method further.
for the moment, here is the output the print() send in my console :
0
Tissu 1 0
0
Tissu 3 0
0
So here I am, it's been 2 days since I've tried evrything I found on the web but nothing...
A little help would be very appreciated
PS: sorry if my english is not perfect :)

tkinter callback through an error: "Index 0 out of range"

I searched for hours what the heck is the reason for this error message:
I have a search entry, which update a listbox depending on my search with a callback function:
Listbox:
self.name_search=tk.StringVar()
self.name_search.trace_add('write', self.my_callback)
self.e_name_search_text = tk.Label(search_f, text="Name: ").grid(row=0, column=0, padx=10, pady=5, sticky='E')
self.e_name_search = ttk.Entry(search_f, width = 35, textvariable=self.name_search)
self.e_name_search.grid(row=0, column=1, padx=5, pady=5, sticky='W')
self.lbox = tk.Listbox(search_f, width=35, height=8)
self.lbox.bind("<Double-Button-1>", self.show_name_search)
self.lbox.bind('<Return>', self.show_name_search)
self.scrollbar = tk.Scrollbar(search_f)
self.lbox.grid(row=1, column=1, rowspan=3, padx=10, pady=1)
self.lbox.config(yscrollcommand = self.scrollbar.set)
self.scrollbar.grid(row=1, column=2, rowspan=3, padx=1, pady=1, sticky='ns')
self.scrollbar.config(command=self.lbox.yview)
So If I type my search, the listbox show me a reduced list of values out of my sqlite database, I am interessed in. If I select one with dobble click. Another sqlite query update my comboboxes.
If I select one I get this error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python38-32\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "D:\... name.py", line 337, in show_name_search
self.e_fax.current(0)
File "C:\Python38-32\lib\tkinter\ttk.py", line 717, in current
return self.tk.call(self._w, "current", newindex)
_tkinter.TclError: Index 0 out of range
Line 337 comes from another function:
def show_name_search(self, event):
self.clear_field()
widget = event.widget
selection = widget.curselection()
indName = widget.get(selection[0])
print(indName)
print("selktierter Wert: {}".format(indName))
self.realName.set(indName)
connection = sqlite3.connect(select_connect_db)
print('Database connected.')
with connection:
cursor = connection.cursor()
cursor.execute("SELECT number, type, prio, id, uniqueid FROM numbers WHERE realName=?;",(indName,))
data = cursor.fetchall()
print(data)
for row in data:
if row[1] == 'home':
self.phone_home.append(row[0])
print('HOME:',self.phone_home)
if row[1] == 'mobile':
self.mobile.append(row[0])
print('Mobile:',self.mobile)
if row[1] == 'work':
self.business.append(row[0])
print(row[0])
print('WORK:',self.business)
if row[1] == 'fax_work':
self.fax.append(row[0])
print(row[0])
print('FAX_WORK:',self.fax)
self.uid_name.set(row[4])
if len(self.phone_home) != 0:
self.e_phone['values'] = self.phone_home
self.e_phone.current(0)
if len(self.mobile) != 0:
self.e_mobile['values'] = self.mobile
self.e_mobile.current(0)
if len(self.business) != 0:
self.e_business['values'] = self.business # Set the value to the new list
self.e_business.current(0) # Set the first item of the list as current item
if len(self.business) != 0:
self.e_fax['values'] = self.fax
self.e_fax.current(0) ### Line 337 - No entry for this value in my sqlite database
Any idea, what I can search for ?
So self.e_faxseems like a ttk.Combobox to me. Consider this code here:
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
values = []
lb = ttk.Combobox(root,values=values)
lb.current(0)
lb.pack()
root.mainloop()
it throughs the same Error:
_tkinter.TclError: Index 0 out of range
and the reason is the list values is empty, insert any regular string in it and it works.
Make sure if you want to set default value that there is an value.
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
values = ['see']
lb = ttk.Combobox(root,values=values)
lb.current(0)
lb.pack()
root.mainloop()

wxpython wx.combobox save wx.StaticText view help me

import wx
import sqlite3
class Frame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None)
self.panel = wx.Panel(self)
self.text = wx.StaticText(self.panel)
self.conn = sqlite3.connect("test.db")
self.cursor = self.conn.cursor()
self.autoRefersh()
def autoRefersh(self):
self.LoadList()
wx.CallLater(1000, self.autoRefersh)
def LoadList(self):
self.cursor.execute("SELECT *FROM CLINIC1")
for date1 in self.cursor: pass
self.staticText2_1 = wx.StaticText(self.panel, label=date1[1], style=wx.ALIGN_CENTER, pos=(100,100))
if __name__ == '__main__':
app = wx.App()
frame = Frame()
frame.Show()
app.MainLoop()
combobox data sqlite3 save in why panel show Why it looks different bug??
I do not know why this is happening.
You missed one crucial step, getting the data itself.
You are using the cursor object not the data returned by the cursor.
def LoadList(self):
self.cursor.execute("SELECT *FROM CLINIC1")
data = self.cursor.fetchall()
for date1 in data: pass
self.staticText2_1 = wx.StaticText(self.panel, label=date1[1], style=wx.ALIGN_CENTER, pos=(100,100))
AS you are "passing" in your for loop perhaps what you actually want is only a single record, in which case
data = self.cursor.fetchone()
and drop the for loop
Even better, read the tutorial
https://www.blog.pythonlibrary.org/2012/07/18/python-a-simple-step-by-step-sqlite-tutorial/
In the heading of your question you mention combobox, so I assume that you want to replace the statictext with a combobox. The following should get you started, I'll leave the wx.EVT_COMBOBOX event binding for you to add, as you will need it to do something when you select an item.
import wx
import sqlite3
class Frame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None)
self.selected_data=[]
self.panel = wx.Panel(self)
self.combo = wx.ComboBox(self.panel,-1,choices=self.selected_data, size=(130,30))
self.conn = sqlite3.connect("test.db")
self.cursor = self.conn.cursor()
self.combo.SetValue("Choose an Item")
self.autoRefresh()
def autoRefresh(self):
self.LoadList()
def LoadList(self):
self.combo.Clear()
self.cursor.execute("SELECT * FROM CLINIC1")
data = self.cursor.fetchall()
for date1 in data:
self.selected_data.append(date1[1])
for i in self.selected_data:
self.combo.Append(i)
if __name__ == '__main__':
app = wx.App()
frame = Frame()
frame.Show()
app.MainLoop()
Edit:
It should look like this.

How to show a QDialog

I need to show a find dialog after pressing Ctrl+F in QWidget, which contains a QTableView. The find dialog will search in the first column of the table to find the matches.
I can show the QMessageBox after pressing Ctrl+F with the following code:
class Widget(QWidget):
def __init__(self,md,parent=None):
QWidget.__init__(self,parent)
layout=QVBoxLayout(self)
# initially construct the visible table
tv = QTableView()
# uncomment this if the last column shall cover the rest
tv.horizontalHeader().setStretchLastSection(True)
tv.show()
# set black grid lines
self.setStyleSheet("gridline-color: rgb(39, 42, 49)")
# construct the Qt model belonging to the visible table
model = NvmQtModel(md)
tv.setModel(model)
tv.resizeRowsToContents()
tv.resizeColumnsToContents()
# set the shortcut ctrl+F for find in menu
shortcut = QShortcut(QKeySequence('Ctrl+f'), self)
shortcut.activated.connect(self.handleFind)
# delegate for decimal
delegate = NvmDelegate()
tv.setItemDelegate(delegate)
self.setGeometry(200,200,600,600) # adjust this later
layout.addWidget(tv)
# set window title
self.setWindowTitle("TITLE")
# find function: search in the first column of the table
def handleFind(self):
reply = QMessageBox.question(
self, 'Find', 'Find Dialog',
QMessageBox.Yes | QMessageBox.No)
if reply == QMessageBox.Yes:
print('Yes')
else:
print('No')
Then I changed the QMessageBox to a QDialog, but now it does not work. I would appreciate if you could tell me where I am not doing it correctly:
class Widget(QWidget):
def __init__(self,md,parent=None):
QWidget.__init__(self,parent)
layout=QVBoxLayout(self)
# initially construct the visible table
tv = QTableView()
# uncomment this if the last column shall cover the rest
tv.horizontalHeader().setStretchLastSection(True)
tv.show()
# set black grid lines
self.setStyleSheet("gridline-color: rgb(39, 42, 49)")
# construct the Qt model belonging to the visible table
model = NvmQtModel(md)
tv.setModel(model)
tv.resizeRowsToContents()
tv.resizeColumnsToContents()
# set the shortcut ctrl+F for find in menu
shortcut = QShortcut(QKeySequence('Ctrl+f'), self)
shortcut.activated.connect(self.handleFind)
# delegate for decimal
delegate = NvmDelegate()
tv.setItemDelegate(delegate)
self.setGeometry(200,200,600,600) # adjust this later
layout.addWidget(tv)
# set window title
self.setWindowTitle("TITLE")
# find function: search in the first column of the table
def handleFind(self):
findDialog = QDialog()
findLabel = QLabel("Find what", findDialog)
findField = QLineEdit(findDialog)
findButton = QPushButton("Find", findDialog)
closeButton = QPushButton("Close", findDialog)
findDialog.show()
If you want the Dialog be a modal Dialog, call findDialog.exec_():
from PyQt4.QtGui import *
def handleFind():
findDialog = QDialog()
#findDialog.setModal(True)
findLabel = QLabel("Find what", findDialog)
findField = QLineEdit(findDialog)
findButton = QPushButton("Find", findDialog)
closeButton = QPushButton("Close", findDialog)
#findDialog.show()
findDialog.exec_()
app = QApplication([])
b = QPushButton("click me")
b.clicked.connect(handleFind)
b.show()
app.exec_()

Can openoffice count words from console?

i have a small problem i need to count words inside the console to read doc, docx, pptx, ppt, xls, xlsx, odt, pdf ... so don't suggest me | wc -w or grep because they work only with text or console output and they count only spaces and in japanese, chinese, arabic , hindu , hebrew they use diferent delimiter so the word count is wrong and i tried to count with this
pdftotext file.pdf -| wc -w
/usr/local/bin/docx2txt.pl < file.docx | wc -w
/usr/local/bin/pptx2txt.pl < file.pptx | wc -w
antiword file.doc -| wc -w
antiword file.word -| wc -w
in some cases microsoft word , openoffice sad 1000 words and the counters return 10 or 300 words if the language is ( japanese , chinese, hindu ect... ) , but if i use normal characters then i have no issue the biggest mistake is in some case 3 chars less witch is "OK"
i tried to convert with soffice , openoffice and then try WC -w but i can't even convert ,
soffice --headless --nofirststartwizard --accept=socket,host=127.0.0.1,port=8100; --convert-to pdf some.pdf /var/www/domains/vocabridge.com/devel/temp_files/23/0/东京_1000_words_Docx.docx
OR
openoffice.org --headless --convert-to ........
OR
openoffice.org3 --invisible
so if someone know any way to count correctly or display document statistic with openoffice or anything else or linux with the console please share it
thanks.
If you have Microsoft Word (and Windows, obviously) you can write a VBA macro or if you want to run straight from the command line you can write a VBScript script with something like the following:
wordApp = CreateObject("Word.Application")
doc = ... ' open up a Word document using wordApp
docWordCount = doc.Words.Count
' Rinse and repeat...
If you have OpenOffice.org/LibreOffice you have similar (but more) options. If you want to stay in the office app and run a macro you can probably do that. I don't know the StarBasic API well enough to tell you how but I can give you the alternative: creating a Python script to get the word count from the command line. Roughly speaking, you do the following:
Start up your copy of OOo/LibO from the command line with the appropriate parameters to accept incoming socket connections. http://www.openoffice.org/udk/python/python-bridge.html has instructions on how to do that. Go there and use the browser's in-page find feature to search for `accept=socket'
Write a Python script to use the OOo/LibO UNO bridge (basically equivalent to the VBScript example above) to open up your Word/ODT documents one at a time and get the word count from each. The above page should give you a good start to doing that.
You get the word count from a document model object's WordCount property: http://www.openoffice.org/api/docs/common/ref/com/sun/star/text/GenericTextDocument.html#WordCount
Just building on to what #Yawar wrote. Here is is more explicit steps for how to word count with MS word from the console.
I also use the more accurate Range.ComputeStatistics(wdStatisticWords) instead of the Words property. See here for more info: https://support.microsoft.com/en-za/help/291447/word-count-appears-inaccurate-when-you-use-the-vba-words-property
Make a script called wc.vbs and then put this in it:
Set word = CreateObject("Word.Application")
word.Visible = False
Set doc = word.Documents.Open("<replace with absolute path to your .docx/.pdf>")
docWordCount = doc.Range.ComputeStatistics(wdStatisticWords)
word.Quit
Dim StdOut : Set StdOut = CreateObject("Scripting.FileSystemObject").GetStandardStream(1)
WScript.Echo docWordCount & " words"
Open powershell in the directory you saved wc.vbs and run cscript .\wc.vbs and you'll get back the word count :)
I think this may do what you are aiming for
# Continuously updating word count
import unohelper, uno, os, time
from com.sun.star.i18n.WordType import WORD_COUNT
from com.sun.star.i18n import Boundary
from com.sun.star.lang import Locale
from com.sun.star.awt import XTopWindowListener
#socket = True
socket = False
localContext = uno.getComponentContext()
if socket:
resolver = localContext.ServiceManager.createInstanceWithContext('com.sun.star.bridge.UnoUrlResolver', localContext)
ctx = resolver.resolve('uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext')
else: ctx = localContext
smgr = ctx.ServiceManager
desktop = smgr.createInstanceWithContext('com.sun.star.frame.Desktop', ctx)
waittime = 1 # seconds
def getWordCountGoal():
doc = XSCRIPTCONTEXT.getDocument()
retval = 0
# Only if the field exists
if doc.getTextFieldMasters().hasByName('com.sun.star.text.FieldMaster.User.WordCountGoal'):
# Get the field
wordcountgoal = doc.getTextFieldMasters().getByName('com.sun.star.text.FieldMaster.User.WordCountGoal')
retval = wordcountgoal.Content
return retval
goal = getWordCountGoal()
def setWordCountGoal(goal):
doc = XSCRIPTCONTEXT.getDocument()
if doc.getTextFieldMasters().hasByName('com.sun.star.text.FieldMaster.User.WordCountGoal'):
wordcountgoal = doc.getTextFieldMasters().getByName('com.sun.star.text.FieldMaster.User.WordCountGoal')
wordcountgoal.Content = goal
# Refresh the field if inserted in the document from Insert > Fields >
# Other... > Variables > Userdefined fields
doc.TextFields.refresh()
def printOut(txt):
if socket: print txt
else:
model = desktop.getCurrentComponent()
text = model.Text
cursor = text.createTextCursorByRange(text.getEnd())
text.insertString(cursor, txt + '\r', 0)
def hotCount(st):
'''Counts the number of words in a string.
ARGUMENTS:
str st: count the number of words in this string
RETURNS:
int: the number of words in st'''
startpos = long()
nextwd = Boundary()
lc = Locale()
lc.Language = 'en'
numwords = 1
mystartpos = 1
brk = smgr.createInstanceWithContext('com.sun.star.i18n.BreakIterator', ctx)
nextwd = brk.nextWord(st, startpos, lc, WORD_COUNT)
while nextwd.startPos != nextwd.endPos:
numwords += 1
nw = nextwd.startPos
nextwd = brk.nextWord(st, nw, lc, WORD_COUNT)
return numwords
def updateCount(wordCountModel, percentModel):
'''Updates the GUI.
Updates the word count and the percentage completed in the GUI. If some
text of more than one word is selected (including in multiple selections by
holding down the Ctrl/Cmd key), it updates the GUI based on the selection;
if not, on the whole document.'''
model = desktop.getCurrentComponent()
try:
if not model.supportsService('com.sun.star.text.TextDocument'):
return
except AttributeError: return
sel = model.getCurrentSelection()
try: selcount = sel.getCount()
except AttributeError: return
if selcount == 1 and sel.getByIndex(0).getString == '':
selcount = 0
selwords = 0
for nsel in range(selcount):
thisrange = sel.getByIndex(nsel)
atext = thisrange.getString()
selwords += hotCount(atext)
if selwords > 1: wc = selwords
else:
try: wc = model.WordCount
except AttributeError: return
wordCountModel.Label = str(wc)
if goal != 0:
pc_text = 100 * (wc / float(goal))
#pc_text = '(%.2f percent)' % (100 * (wc / float(goal)))
percentModel.ProgressValue = pc_text
else:
percentModel.ProgressValue = 0
# This is the user interface bit. It looks more or less like this:
###############################
# Word Count _ o x #
###############################
# _____ #
# 451 / |500| #
# ----- #
# ___________________________ #
# |############## | #
# --------------------------- #
###############################
# The boxed `500' is the text entry box.
class WindowClosingListener(unohelper.Base, XTopWindowListener):
def __init__(self):
global keepGoing
keepGoing = True
def windowClosing(self, e):
global keepGoing
keepGoing = False
setWordCountGoal(goal)
e.Source.setVisible(False)
def addControl(controlType, dlgModel, x, y, width, height, label, name = None):
control = dlgModel.createInstance(controlType)
control.PositionX = x
control.PositionY = y
control.Width = width
control.Height = height
if controlType == 'com.sun.star.awt.UnoControlFixedTextModel':
control.Label = label
elif controlType == 'com.sun.star.awt.UnoControlEditModel':
control.Text = label
elif controlType == 'com.sun.star.awt.UnoControlProgressBarModel':
control.ProgressValue = label
if name:
control.Name = name
dlgModel.insertByName(name, control)
else:
control.Name = 'unnamed'
dlgModel.insertByName('unnamed', control)
return control
def loopTheLoop(goalModel, wordCountModel, percentModel):
global goal
while keepGoing:
try: goal = int(goalModel.Text)
except: goal = 0
updateCount(wordCountModel, percentModel)
time.sleep(waittime)
if not socket:
import threading
class UpdaterThread(threading.Thread):
def __init__(self, goalModel, wordCountModel, percentModel):
threading.Thread.__init__(self)
self.goalModel = goalModel
self.wordCountModel = wordCountModel
self.percentModel = percentModel
def run(self):
loopTheLoop(self.goalModel, self.wordCountModel, self.percentModel)
def wordCount(arg = None):
'''Displays a continuously updating word count.'''
dialogModel = smgr.createInstanceWithContext('com.sun.star.awt.UnoControlDialogModel', ctx)
dialogModel.PositionX = XSCRIPTCONTEXT.getDocument().CurrentController.Frame.ContainerWindow.PosSize.Width / 2.2 - 105
dialogModel.Width = 100
dialogModel.Height = 30
dialogModel.Title = 'Word Count'
lblWc = addControl('com.sun.star.awt.UnoControlFixedTextModel', dialogModel, 6, 2, 25, 14, '', 'lblWc')
lblWc.Align = 2 # Align right
addControl('com.sun.star.awt.UnoControlFixedTextModel', dialogModel, 33, 2, 10, 14, ' / ')
txtGoal = addControl('com.sun.star.awt.UnoControlEditModel', dialogModel, 45, 1, 25, 12, '', 'txtGoal')
txtGoal.Text = goal
#addControl('com.sun.star.awt.UnoControlFixedTextModel', dialogModel, 6, 25, 50, 14, '(percent)', 'lblPercent')
ProgressBar = addControl('com.sun.star.awt.UnoControlProgressBarModel', dialogModel, 6, 15, 88, 10,'' , 'lblPercent')
ProgressBar.ProgressValueMin = 0
ProgressBar.ProgressValueMax =100
#ProgressBar.Border = 2
#ProgressBar.BorderColor = 255
#ProgressBar.FillColor = 255
#ProgressBar.BackgroundColor = 255
addControl('com.sun.star.awt.UnoControlFixedTextModel', dialogModel, 124, 2, 12, 14, '', 'lblMinus')
controlContainer = smgr.createInstanceWithContext('com.sun.star.awt.UnoControlDialog', ctx)
controlContainer.setModel(dialogModel)
controlContainer.addTopWindowListener(WindowClosingListener())
controlContainer.setVisible(True)
goalModel = controlContainer.getControl('txtGoal').getModel()
wordCountModel = controlContainer.getControl('lblWc').getModel()
percentModel = controlContainer.getControl('lblPercent').getModel()
ProgressBar.ProgressValue = percentModel.ProgressValue
if socket:
loopTheLoop(goalModel, wordCountModel, percentModel)
else:
uthread = UpdaterThread(goalModel, wordCountModel, percentModel)
uthread.start()
keepGoing = True
if socket:
wordCount()
else:
g_exportedScripts = wordCount,
Link for more info
https://superuser.com/questions/529446/running-word-count-in-openoffice-writer
Hope this helps regards tom
EDIT : Then i found this
http://forum.openoffice.org/en/forum/viewtopic.php?f=7&t=22555
wc can understand Unicode and uses system's iswspace function to find whether the unicode character is whitespace. "The iswspace() function tests whether wc is a wide-character code representing a character of class space in the program's current locale." So, wc -w should be able to correctly count words if your locale (LC_CTYPE) is configured correctly.
The source code of the wc program
The manual page for the iswspace function
I found the answer create one service
#!/bin/sh
#
# chkconfig: 345 99 01
#
# description: your script is a test service
#
(while sleep 1; do
ls pathwithfiles/in | while read file; do
libreoffice --headless -convert-to pdf "pathwithfiles/in/$file" --outdir pathwithfiles/out
rm "pathwithfiles/in/$file"
done
done) &
then the php script that i needed counted everything
$ext = pathinfo($absolute_file_path, PATHINFO_EXTENSION);
if ($ext !== 'txt' && $ext !== 'pdf') {
// Convert to pdf
$tb = mktime() . mt_rand();
$tempfile = 'locationofpdfs/in/' . $tb . '.' . $ext;
copy($absolute_file_path, $tempfile);
$absolute_file_path = 'locationofpdfs/out/' . $tb . '.pdf';
$ext = 'pdf';
while (!is_file($absolute_file_path)) sleep(1);
}
if ($ext !== 'txt') {
// Convert to txt
$tempfile = tempnam(sys_get_temp_dir(), '');
shell_exec('pdftotext "' . $absolute_file_path . '" ' . $tempfile);
$absolute_file_path = $tempfile;
$ext = 'txt';
}
if ($ext === 'txt') {
$seq = '/[\s\.,;:!\? ]+/mu';
$plain = file_get_contents($absolute_file_path);
$plain = preg_replace('#\{{{.*?\}}}#su', "", $plain);
$str = preg_replace($seq, '', $plain);
$chars = count(preg_split('//u', $str, -1, PREG_SPLIT_NO_EMPTY));
$words = count(preg_split($seq, $plain, -1, PREG_SPLIT_NO_EMPTY));
if ($words === 0) return $chars;
if ($chars / $words > 10) $words = $chars;
return $words;
}

Resources