Python cannot edit word document - python-3.8

my goal is to replace some text within an existing word docx. However, I have experienced error while using ReplaceAll function. Could you please help to explain the issue? thank you!
my code:
import win32com.client
constants=win32com.client.constants
wordapp=win32com.client.gencache.EnsureDispatch('Word.Application')
worddoc=wordapp.Documents.Open(templatefile)
wordapp.Visible=False
wordapp.Selection.Find.ClearFormatting
wordapp.Selection.Find.Replacement.ClearFormatting
worddoc.Range(0,0).Select()
selection = wordapp.Selection
selection.Find.ClearFormatting()
selection.Find.Replacement.ClearFormatting()
selection.Find.Forward=True
for dummy in myDict.keys():
selection.Find.Text = dummy
selection.Find.Replacement.Text = myDict[dummy]
selection.Find.Execute(Replace=constants.wdReplaceAll)
worddoc.SaveAs(savefile)
worddoc.Close()
wordapp.Application.Quit()
error message:
Traceback (most recent call last):
File "short_py3_1.py", line 75, in <module>
selection.Find.Execute(Replace=constants.wdReplaceAll)
File "C:\Temp\gen_py\3.8\00020905-0000-0000-C000-000000000046x0x8x7\Find.py", line 45, in Execute
return self._oleobj_.InvokeTypes(444, LCID, 1, (11, 0), ((16396, 17), (16396, 17), (16396, 17), (16396, 17), (16396, 17), (16396, 17), (16396, 17), (16396, 17), (16396, 17), (16396, 17), (16396, 17), (16396, 17), (16396, 17), (16396, 17), (16396, 17)),FindText
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Word', 'This command is not available.', 'wdmain11.chm', 37373, -2146823683), None)
my conda package:
ca-certificates 2021.1.19 h9f7ea03_0
certifi 2020.12.5 py38h9f7ea03_0
openssl 1.1.1i hc431981_0
pip 20.3.3 py38h9f7ea03_0
pysimplegui 4.34.0 pypi_0 pypi
python 3.8.5 h5fd99cc_1
pywin32 227 py38he774522_1
setuptools 51.3.3 py38h9f7ea03_4
sqlite 3.33.0 h2a8f88b_0
vc 14.2 h21ff451_1
vs2015_runtime 14.27.29016 h5e58377_2
wheel 0.36.2 pyhd3eb1b0_0
wincertstore 0.2 py38_0
zlib 1.2.11 h33f27b4_4

Sorry, I just figured out myself. the issue is when open word 2019, the program has an default view of "read" mode (which prevents the user to modify the document. you can switch the mode at the right bottom corner of word). Then I changed the word default view from read mode to print layout in word option. the script ran without the error.
more information on "How Do You Make Print Layout the Default View Layout in Microsoft Word?"
Link

Related

AttributeError: module 'numpy' has no attribute 'float'. Did you mean: 'cfloat'? [duplicate]

This question already has answers here:
How to solve error 'numpy' has no attribute 'float' in Python?
(3 answers)
Closed last month.
I would like to use scikit-optimize's BayesSearchCV and using the following package versions in my environment myEnv:
# Name Version Build Channel
python 3.10.8 h4a9ceb5_0_cpython conda-forge
numpy 1.24.1 pypi_0 pypi
scikit-optimize 0.8.1 pyh9f0ad1d_0 conda-forge
and I am getting the error
AttributeError: module 'numpy' has no attribute 'float'. Did you mean: 'cfloat'?
FYI: The full error message is as follows
Traceback (most recent call last):
File "/home/ec2-user/anaconda3/envs/myEnv/lib/python3.10/runpy.py", line 196, in _run_module_as_main
return _run_code(code, main_globals, None,
File "/home/ec2-user/anaconda3/envs/myEnv/lib/python3.10/runpy.py", line 86, in _run_code
exec(code, run_globals)
File "/home/ec2-user/anaconda3/envs/myEnv/lib/python3.10/site-packages/sklearnex/__main__.py", line 55, in <module>
sys.exit(_main())
File "/home/ec2-user/anaconda3/envs/myEnv/lib/python3.10/site-packages/sklearnex/__main__.py", line 52, in _main
runf(args.name, run_name='__main__')
File "/home/ec2-user/anaconda3/envs/myEnv/lib/python3.10/runpy.py", line 289, in run_path
return _run_module_code(code, init_globals, run_name,
File "/home/ec2-user/anaconda3/envs/myEnv/lib/python3.10/runpy.py", line 96, in _run_module_code
_run_code(code, mod_globals, init_globals,
File "/home/ec2-user/anaconda3/envs/myEnv/lib/python3.10/runpy.py", line 86, in _run_code
exec(code, run_globals)
File "bayes_helper.py", line 26, in <module>
from skopt import BayesSearchCV
File "/home/ec2-user/anaconda3/envs/myEnv/lib/python3.10/site-packages/skopt/__init__.py", line 44, in <module>
from . import callbacks
File "/home/ec2-user/anaconda3/envs/myEnv/lib/python3.10/site-packages/skopt/callbacks.py", line 17, in <module>
from skopt.utils import dump
File "/home/ec2-user/anaconda3/envs/myEnv/lib/python3.10/site-packages/skopt/utils.py", line 19, in <module>
from .sampler import Sobol, Lhs, Hammersly, Halton, Grid
File "/home/ec2-user/anaconda3/envs/myEnv/lib/python3.10/site-packages/skopt/sampler/__init__.py", line 4, in <module>
from .lhs import Lhs
File "/home/ec2-user/anaconda3/envs/myEnv/lib/python3.10/site-packages/skopt/sampler/lhs.py", line 9, in <module>
from ..space import Space, Categorical
File "/home/ec2-user/anaconda3/envs/myEnv/lib/python3.10/site-packages/skopt/space/__init__.py", line 5, in <module>
from .space import *
File "/home/ec2-user/anaconda3/envs/myEnv/lib/python3.10/site-packages/skopt/space/space.py", line 212, in <module>
class Real(Dimension):
File "/home/ec2-user/anaconda3/envs/myEnv/lib/python3.10/site-packages/skopt/space/space.py", line 253, in Real
name=None, dtype=np.float):
File "/home/ec2-user/anaconda3/envs/myEnv/lib/python3.10/site-packages/numpy/__init__.py", line 284, in __getattr__
raise AttributeError("module {!r} has no attribute "
AttributeError: module 'numpy' has no attribute 'float'. Did you mean: 'cfloat'?
It seems that there is some compatibility issue between my numpy version and my scikit-optimize version. But I don't find what it is. In the scikit-optimize documentation it just says that NumPy (>= 1.13.3) is required. Which is the case for me. I also tried it with the very latest version of scikit-optimize which is 0.0.9, but I still get this error.
Can anyone help me with solving this issue? I can provide any other package version information if needed.
NumPy abolished types like np.int and np.float, they are deprecated since 1.20, instead standard builtin types int, float or special types like np.int32 should be used.
In short your scikit-optimize and NumPy versions are not compatible.
First you could try to update the package to the newest version of 0.9.
As well can edit that line of code manually in your installation (replace it with float) and test if it works (chance is high).
Else downgrade your numpy to below 1.20. Below 1.24 it still works but will give you a warning

Can't visualize plotted Confusion Matrix

I am new to ML and learning the fundamentals.
I am working on Dog-vision dataset (https://www.kaggle.com/c/dog-breed-identification) and I am trying to plot a confusion matrix but can't get where I am doing wrong, need help!
My true_label looks like this
true_label[:10]
array([26, 96, 8, 15, 3, 10, 62, 82, 92, 16]
And predicted_label looks like this
predicted_l[:10]
array([26, 96, 8, 15, 3, 10, 62, 82, 92, 16]
They are almost same but not the whole elements in the array are same.
Then I had converted them into a panda dataframe, with code like this
import pandas as pd
from sklearn.metrics import confusion_matrix
classes=[]
for i in range(0, 99):
classes.append(i)
cf_matrix = confusion_matrix(true_l, predicted_l)
cf_matrix_df = pd.DataFrame(cf_matrix, index=classes,columns=classes)
cf_matrix_df
And then the output is like this-
Then I tried to plot the confusion matrix with this dataframe
but it's not being plotted in correct manner. Here is the code and the output of my confusion matrix:-
import seaborn as sns
figure = plt.figure(figsize=(8, 8))
sns.heatmap(cf_matrix_df, annot=True,cmap=plt.cm.Blues)
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
plt.show()
Output
If you need more info then please have a look on my notebook here.
https://colab.research.google.com/drive/1SoXJJNTnGx39uZHizAut-HuMtKhQQolk?usp=sharing
You can make your plot better by removing annot=True argument, since it writes the data value in each cell. Simply remove this argument to get a better visualization:
sns.heatmap(cf_matrix_df, cmap=plt.cm.Blues)
UPDATE: Increasing the figure size figsize() will help to make visualization more clearer.

How to use multiple versions of Tensorflow in same project?

I'm using Tensorflow 1.9.0 version which is built with AVX support, but when I'm packaging the project into an EXE and testing on another machine it crashes due to not having AVX support on this machine. so I revert back to Tensorflow 1.5 and it worked fine.
Now the question is can I switch to the desired Tensorflow version after detecting the AVX support in machine dynamically (on run time).
I don't know how to switch version so didn't try but I'm detecting the AVX support. like this
>>> import cpuinfo
>>> cpuinfo.get_cpu_info()
{'python_version': '3.6.5.final.0 (64 bit)',
'cpuinfo_version': [5, 0, 0], 'arch': 'X86_64', 'bits': 64, 'count': 4, 'raw_arch_string': 'AMD64', 'vendor_id': 'GenuineIntel',
'brand': 'Intel(R) Core(TM) i3-2350M CPU # 2.30GHz', 'hz_advertised': '2.3000 GHz', 'hz_actual': '1.6000 GHz', 'hz_advertised_raw': [2300000000, 0], 'hz_actual_raw': [1600000000, 0], 'l2_cache_size': '512 KB', 'stepping': 7, 'model': 42, 'family': 6, 'l3_cache_size': '3072 KB',
'flags': ['acpi', 'apic', 'avx', 'clflush', 'cmov', 'cx16', 'cx8', 'de', 'ds_cpl', 'dtes64', 'dts', 'est', 'fpu', 'fxsr', 'ht', 'ia64', 'lahf_lm', 'mca', 'mce', 'mmx', 'monitor', 'msr', 'mtrr', 'osxsave', 'pae', 'pat', 'pbe', 'pcid', 'pclmulqdq', 'pdcm', 'pge', 'pni', 'popcnt', 'pse', 'pse36', 'sep', 'serial', 'ss', 'sse', 'sse2', 'sse4_1', 'sse4_2', 'ssse3', 'tm', 'tm2', 'tsc', 'tscdeadline', 'vme', 'vmx', 'x2apic', 'xsave', 'xtpr'],
'l2_cache_line_size': 6, 'l2_cache_associativity': '0x100', 'extended_model': 2}
I want to package both (AVX support and unsupported) versions in same EXE and use it according to the needs. Any other suggestions are welcomed.
Thanks
Your question contains part of the answer. From cpuinfo.get_cpu_info(), you will get whether AVX is supported or not(mentioned in 'flags'). Accordingly, you can install the required packages inside the python code itself( Refer Installing python module within code for details).
Alternatively, you can do the same thing from terminal. grep flags /proc/cpuinfo will give you flags supported. Depending on if avx is there or not, create a script to install tensorflow of the appropriate version

Odoo: External API: TypeError: cannot marshal <class 'datetime.date'> objects

with our slightly modified Odoo (V12), we are trying to fetch Data via external API from odoo.
while fetching res.partner we get following Error:
TypeError: cannot marshal <class 'datetime.date'> objects
the fetched Object has the following datetime/date values
'write_date': datetime.datetime(2018, 10, 16, 11, 56, 51, 417000),
'uid_nr_check': datetime.date(2018, 10, 1),
'__last_update': datetime.datetime(2018, 10, 16, 11, 56, 51, 417000),
uid_nr_check is defined as:
uid_nr_check = fields.Date(string="last UID Number check")
any ideas whats wrong? we use nighly build of odoo 12 on debian.

Scaling scatter plot in IPython Notebook

I'm running an IPython Notebook:
$ ipython notebook --pylab inline
Is it possible to scale plots or images which are inline?
E.g. I have
pylab.xlabel("Label X")
pylab.ylabel("Label Y")
pylab.scatter(range(2,15,2), [2, 3, 5, 7, 11, 13, 17], c="r")
and I want to have it bigger.
Sure, I can try to manually change parameters, e.g.
pylab.figure(figsize=(12, 8))
pylab.xlabel("Label X", fontsize = 20)
pylab.ylabel("Label Y", fontsize = 20)
pylab.scatter(range(2,15,2), [2, 3, 5, 7, 11, 13, 17], c="r", s=100)
but it's neither convenient nor exact.
In Python v2.7.4 running IPython v0.13 with matplotlib v1.2.0 32-bit on Windows 8, I get a "handle" in the lower right corner to manually resize (keep aspect ratio and resolution) the inline plot, at least when the figure_format in use is 'png'. As for the other formats I'm not sure, but it appears that this behavior is not present when 'svg' is used.
You can change the default figure_format by uncommenting the line starting with
# c.InlineBackend.figure_format
in the config-file ipython_notebook_config.py in your profile-folder for IPython, and set this parameter to whatever format you want to use when running the notebook, e.g. 'png'.
If you want to change the default size of all inline plots, you can change the parameter c.InlineBackend.rc in the same config-file. If you e.g. want to set the figsize to (12, 8), you simply uncomment the relevant line in the file, making it say
c.InlineBackend.rc = {'figure.figsize': (12, 8)}
This parameter can also change the default fontsize, dpi, etc.