Python-docx how to modify data of charts? - ms-word

I added a chart in docx, and I hope I can edit the data to change histogram bins length.
How can I do it?
#scanny This is the code I tried, and show me error is
chart.replace_data(chart_data) AttributeError: 'module' object has no
attribute 'replace_data'
import docx
import os
import sys
import csv
import datetime
import time
import pptx
from pptx import chart
from pptx.chart import data
from pptx.chart.data import CategoryChartData
CURRENT_DIR = os.path.dirname(os.path.abspath(sys.argv[0]))
docxFilePath = os.path.join(CURRENT_DIR,'sample.docx')
chart_data = CategoryChartData()
chart_data.categories = ['East', 'West', 'Midwest']
chart_data.add_series('Series 1', (19.2, 21.4, 16.7))
chart.replace_data(chart_data)
filename ='test.docx'
filepath = os.path.join(r'C:\Users\Administrator\Desktop\python test\update_test', filename)
doc.save(filepath)

Charts in python-pptx are updated by populating a new ChartData object and passing it to chart.replace_data:
from pptx.chart.data import CategoryChartData
chart_data = CategoryChartData()
chart_data.categories = ['East', 'West', 'Midwest']
chart_data.add_series('Series 1', (19.2, 21.4, 16.7))
chart.replace_data(chart_data)

Related

Empty array returned when calling AlphaVantage APIs for NSE symbols tickers

I cannot get any NSE Symbol data from the AlphaVantage, they return always empty array.
Query:
https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=NSE:TITAN&apikey=Q134IXR7RVWU5AQL&outputsize=full&interval=1min
Response:
{}
A month back the same query was returning data.
Looks something has changed on the AlphaVantage server end recently.
Your help is much appreciated in advance!
Try this
import pandas as pd
import json
import requests
import datetime
from pandas import DataFrame
from datetime import datetime as dt
from alpha_vantage.timeseries import TimeSeries
stock_ticker = 'SPY'
api_key = 'Q134IXR7RVWU5AQL'
ts = TimeSeries (key=api_key, output_format = "pandas")
data_daily, meta_data = ts.get_intraday(symbol=stock_ticker, interval ='1min', outputsize ='full')
print(data_daily)
The output for me looks like this

Receiving "Workbook.getWorkbook() is applicable for argument types: (java.io.File) values:" while reading excel using Groovy from SoapUI

Could you anyone please findout the rootcause of the below error
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.util.*;
import org.apache.poi.ss.usermodel.*;
import java.io.*;
//def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)
File file=new File("C://Users/toothless/Desktop/Don Delete/MyPractice.xlsx")
Workbook workbook = Workbook.getWorkbook(file)
Sheet sheet=workbook.getSheet(0)
rc=sheet.getRows()
log.info rc
Following is my ext folder screenshot.
I'm getting the following error while executing the above groovy code.
groovy.lang.MissingMethodException: No signature of method: static org.apache.poi.ss.usermodel.Workbook.getWorkbook() is applicable for argument types: (java.io.File) values: [C:\Users\toothless\Desktop\Don Delete\MyPractice.xlsx] error at line: 10
First there is no method like you mention Workbook.getWorkbook. Ref doc. Here your question to read excel file as workbook object use the code shown below,
For xlsx files :
XSSFWorkbook wb = new XSSFWorkbook (file)
For xls files :
HSSFWorkbook wb = new HSSFWorkbook (file)
After that you can use these methods shown in doc for further reading process.

How to store Images in MongoDB through pymongo?

from PIL import Image
from bson import Binary
img = Image.open('test.jpg')
img = Binary(img)
throws an error stating TypeError : data must be an instance of bytes
Why does this happen? And how to resolve this to store the img to MongoDB?
As long as the document doesn't exceed 16MB standard bson is fine, otherwise gridfs should be used. The example below shows how an image can be inserted and read back from a mongodb.
insert_image.py
from pymongo import MongoClient
from PIL import Image
import io
client = MongoClient()
db = client.testdb
images = db.images
im = Image.open("./image.jpg")
image_bytes = io.BytesIO()
im.save(image_bytes, format='JPEG')
image = {
'data': image_bytes.getvalue()
}
image_id = images.insert_one(image).inserted_id
read_image.py
from pymongo import MongoClient
from bson.binary import Binary
from PIL import Image
import io
import matplotlib.pyplot as plt
client = MongoClient()
db = client.testdb
images = db.images
image = images.find_one()
pil_img = Image.open(io.BytesIO(image['data']))
plt.imshow(pil_img)
plt.show()
You need to convert the image into a Byte array. You can do this as follows,
from PIL import Image
from bson import Binary
img = Image.open('test.jpg')
imgByteArr = io.BytesIO()
img.save(imgByteArr, format='PNG')
imgByteArr = imgByteArr.getvalue()
You can try to save imgByteArr into mongo
OR
You can convert image into string and then store it in mongo:
import base64
with open("test.jpg", "rb") as imageFile:
str = base64.b64encode(imageFile.read())
//store str in mongo
To get back image
with open("test2.jpg", "wb") as fimage:
fimage.write(str.decode('base64'))

backoff_tagger not defined error

Hi I'm trying to use Brill Tagger to tag a set of sentences. But when running the following ,
=======================
Training a Brill Tagger
>>> default_tagger = DefaultTagger('NN')
>>> initial_tagger = backoff_tagger(train_sents, [UnigramTagger, BigramTagger, TrigramTagger], backoff=default_tagger)
>>> initial_tagger.evaluate(test_sents)
0.8806820634578028
>>> from tag_util import train_brill_tagger
>>> brill_tagger = train_brill_tagger(initial_tagger, train_sents)
>>> brill_tagger.evaluate(test_sents)
0.8827541549751781
I'm getting the following error.
NameError: name 'backoff_tagger' is not defined
what are the causes for this. Do I need to import something
I think you need to import the following:
from tag_util import backoff_tagger

Linking weka to matlab

I have written this code in Matlab to link weka with matlab so that i can implement Genetic Algorithm
enter code here
import java.util.*
import java.util.Enumeration
import java.lang.String
import weka.classifiers.*
import weka.classifiers.Evaluation
import weka.classifiers.trees.J48
import java.io.FileReader
import weka.core.Instances
import weka.core.Utils
import weka.core.Attribute
import java.lang.System
javaaddpath('C:\Users\sagnik\Documents\MATLAB\GA\weka.jar');
clear all
clc
v1 = java.lang.String('-t');
v2 = java.lang.String('C:\Users\sagnik\Documents\MATLAB\GA\generateTrainDiv.csv');
v3 = java.lang.String('-T');
v4 = java.lang.String('C:\Users\sagnik\Documents\MATLAB\GA\generateTestDiv.csv');
prm = cat(1,v1,v2,v3,v4);
classifier = javaObject('weka.classifiers.functions.MultilayerPerceptron');
weka.classifiers.Evaluation.evaluateModel(classifier,prm);
But this is giving error in the last line as:
Java exception occurred:
java.lang.Exception:
Weka exception: Can't open file null.
at weka.classifiers.Evaluation.evaluateModel(Evaluation.java:1080)
Please somenone help me,how to fix this! How is the filename 'null' here..I have already provided the 2 filenames..