I am receiving the following error when importing pandas in a Python program
monas-mbp:book mona$ sudo pip install python-dateutil
Requirement already satisfied (use --upgrade to upgrade): python-dateutil in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python
Cleaning up...
monas-mbp:book mona$ python t1.py
No module named dateutil.parser
Traceback (most recent call last):
File "t1.py", line 4, in <module>
import pandas as pd
File "/Library/Python/2.7/site-packages/pandas/__init__.py", line 6, in <module>
from . import hashtable, tslib, lib
File "tslib.pyx", line 31, in init pandas.tslib (pandas/tslib.c:48782)
ImportError: No module named dateutil.parser
Also here's the program:
import codecs
from math import sqrt
import numpy as np
import pandas as pd
users = {"Angelica": {"Blues Traveler": 3.5, "Broken Bells": 2.0,
"Norah Jones": 4.5, "Phoenix": 5.0,
"Slightly Stoopid": 1.5,
"The Strokes": 2.5, "Vampire Weekend": 2.0},
"Bill":{"Blues Traveler": 2.0, "Broken Bells": 3.5,
"Deadmau5": 4.0, "Phoenix": 2.0,
"Slightly Stoopid": 3.5, "Vampire Weekend": 3.0},
"Chan": {"Blues Traveler": 5.0, "Broken Bells": 1.0,
"Deadmau5": 1.0, "Norah Jones": 3.0, "Phoenix": 5,
"Slightly Stoopid": 1.0},
"Dan": {"Blues Traveler": 3.0, "Broken Bells": 4.0,
"Deadmau5": 4.5, "Phoenix": 3.0,
"Slightly Stoopid": 4.5, "The Strokes": 4.0,
"Vampire Weekend": 2.0},
"Hailey": {"Broken Bells": 4.0, "Deadmau5": 1.0,
"Norah Jones": 4.0, "The Strokes": 4.0,
"Vampire Weekend": 1.0},
"Jordyn": {"Broken Bells": 4.5, "Deadmau5": 4.0,
"Norah Jones": 5.0, "Phoenix": 5.0,
"Slightly Stoopid": 4.5, "The Strokes": 4.0,
"Vampire Weekend": 4.0},
"Sam": {"Blues Traveler": 5.0, "Broken Bells": 2.0,
"Norah Jones": 3.0, "Phoenix": 5.0,
"Slightly Stoopid": 4.0, "The Strokes": 5.0},
"Veronica": {"Blues Traveler": 3.0, "Norah Jones": 5.0,
"Phoenix": 4.0, "Slightly Stoopid": 2.5,
"The Strokes": 3.0}
}
class recommender:
def __init__(self, data, k=1, metric='pearson', n=5):
""" initialize recommender
currently, if data is dictionary the recommender is initialized
to it.
For all other data types of data, no initialization occurs
k is the k value for k nearest neighbor
metric is which distance formula to use
n is the maximum number of recommendations to make"""
self.k = k
self.n = n
self.username2id = {}
self.userid2name = {}
self.productid2name = {}
# for some reason I want to save the name of the metric
self.metric = metric
if self.metric == 'pearson':
self.fn = self.pearson
#
# if data is dictionary set recommender data to it
#
if type(data).__name__ == 'dict':
self.data = data
def convertProductID2name(self, id):
"""Given product id number return product name"""
if id in self.productid2name:
return self.productid2name[id]
else:
return id
def userRatings(self, id, n):
"""Return n top ratings for user with id"""
print ("Ratings for " + self.userid2name[id])
ratings = self.data[id]
print(len(ratings))
ratings = list(ratings.items())
ratings = [(self.convertProductID2name(k), v)
for (k, v) in ratings]
# finally sort and return
ratings.sort(key=lambda artistTuple: artistTuple[1],
reverse = True)
ratings = ratings[:n]
for rating in ratings:
print("%s\t%i" % (rating[0], rating[1]))
def loadBookDB(self, path=''):
"""loads the BX book dataset. Path is where the BX files are
located"""
self.data = {}
i = 0
#
# First load book ratings into self.data
#
f = codecs.open(path + "BX-Book-Ratings.csv", 'r', 'utf8')
for line in f:
i += 1
#separate line into fields
fields = line.split(';')
user = fields[0].strip('"')
book = fields[1].strip('"')
rating = int(fields[2].strip().strip('"'))
if user in self.data:
currentRatings = self.data[user]
else:
currentRatings = {}
currentRatings[book] = rating
self.data[user] = currentRatings
f.close()
#
# Now load books into self.productid2name
# Books contains isbn, title, and author among other fields
#
f = codecs.open(path + "BX-Books.csv", 'r', 'utf8')
for line in f:
i += 1
#separate line into fields
fields = line.split(';')
isbn = fields[0].strip('"')
title = fields[1].strip('"')
author = fields[2].strip().strip('"')
title = title + ' by ' + author
self.productid2name[isbn] = title
f.close()
#
# Now load user info into both self.userid2name and
# self.username2id
#
f = codecs.open(path + "BX-Users.csv", 'r', 'utf8')
for line in f:
i += 1
#print(line)
#separate line into fields
fields = line.split(';')
userid = fields[0].strip('"')
location = fields[1].strip('"')
if len(fields) > 3:
age = fields[2].strip().strip('"')
else:
age = 'NULL'
if age != 'NULL':
value = location + ' (age: ' + age + ')'
else:
value = location
self.userid2name[userid] = value
self.username2id[location] = userid
f.close()
print(i)
def pearson(self, rating1, rating2):
sum_xy = 0
sum_x = 0
sum_y = 0
sum_x2 = 0
sum_y2 = 0
n = 0
for key in rating1:
if key in rating2:
n += 1
x = rating1[key]
y = rating2[key]
sum_xy += x * y
sum_x += x
sum_y += y
sum_x2 += pow(x, 2)
sum_y2 += pow(y, 2)
if n == 0:
return 0
# now compute denominator
denominator = (sqrt(sum_x2 - pow(sum_x, 2) / n)
* sqrt(sum_y2 - pow(sum_y, 2) / n))
if denominator == 0:
return 0
else:
return (sum_xy - (sum_x * sum_y) / n) / denominator
def computeNearestNeighbor(self, username):
"""creates a sorted list of users based on their distance to
username"""
distances = []
for instance in self.data:
if instance != username:
distance = self.fn(self.data[username],
self.data[instance])
distances.append((instance, distance))
# sort based on distance -- closest first
distances.sort(key=lambda artistTuple: artistTuple[1],
reverse=True)
return distances
def recommend(self, user):
"""Give list of recommendations"""
recommendations = {}
# first get list of users ordered by nearness
nearest = self.computeNearestNeighbor(user)
#
# now get the ratings for the user
#
userRatings = self.data[user]
#
# determine the total distance
totalDistance = 0.0
for i in range(self.k):
totalDistance += nearest[i][1]
# now iterate through the k nearest neighbors
# accumulating their ratings
for i in range(self.k):
# compute slice of pie
weight = nearest[i][1] / totalDistance
# get the name of the person
name = nearest[i][0]
# get the ratings for this person
neighborRatings = self.data[name]
# get the name of the person
# now find bands neighbor rated that user didn't
for artist in neighborRatings:
if not artist in userRatings:
if artist not in recommendations:
recommendations[artist] = (neighborRatings[artist]
* weight)
else:
recommendations[artist] = (recommendations[artist]
+ neighborRatings[artist]
* weight)
# now make list from dictionary
recommendations = list(recommendations.items())
recommendations = [(self.convertProductID2name(k), v)
for (k, v) in recommendations]
# finally sort and return
recommendations.sort(key=lambda artistTuple: artistTuple[1],
reverse = True)
# Return the first n items
return recommendations[:self.n]
r = recommender(users)
# The author implementation
r.loadBookDB('/Users/mona/Downloads/BX-Dump/')
ratings = pd.read_csv('/Users/danialt/BX-CSV-Dump/BX-Book-Ratings.csv', sep=";", quotechar="\"", escapechar="\\")
books = pd.read_csv('/Users/danialt/BX-CSV-Dump/BX-Books.csv', sep=";", quotechar="\"", escapechar="\\")
users = pd.read_csv('/Users/danialt/BX-CSV-Dump/BX-Users.csv', sep=";", quotechar="\"", escapechar="\\")
pivot_rating = ratings.pivot(index='User-ID', columns='ISBN', values='Book-Rating')
On Ubuntu you may need to install the package manager pip first:
sudo apt-get install python-pip
Then install the python-dateutil package with:
sudo pip install python-dateutil
For Python 3:
pip3 install python-dateutil
You can find the dateutil package at https://pypi.python.org/pypi/python-dateutil. Extract it to somewhere and run the command:
python setup.py install
It worked for me!
I have same issues on my MacOS and it's work for me to try
pip3 install python-dateutil
on Ubuntu
sudo apt-get install python-dateutil
For Python 3 above, use:
sudo apt-get install python3-dateutil
If you're using a virtualenv, make sure that you are running pip from within the virtualenv.
$ which pip
/Library/Frameworks/Python.framework/Versions/Current/bin/pip
$ find . -name pip -print
./flask/bin/pip
./flask/lib/python2.7/site-packages/pip
$ ./flask/bin/pip install python-dateutil
None of the solutions worked for me. If you are using PIP do:
pip install pycrypto==2.6.1
In Ubuntu 18.04 for Python2:
sudo apt-get install python-dateutil
I had the similar problem. This is the stack trace:
Traceback (most recent call last):
File "/usr/local/bin/aws", line 19, in <module> import awscli.clidriver
File "/usr/local/lib/python2.7/dist-packages/awscli/clidriver.py", line 17, in <module> import botocore.session
File "/usr/local/lib/python2.7/dist-packages/botocore/session.py", line 30, in <module> import botocore.credentials
File "/usr/local/lib/python2.7/dist-packages/botocore/credentials.py", line 27, in <module> from dateutil.parser import parse
ImportError: No module named dateutil.parser
I tried to (re-)install dateutil.parser through all possible ways. It was unsuccessful.
I solved it with
pip3 uninstall awscli
pip3 install awscli
sudo python3 -m pip install PyPDF2 passlib babel werkzeug lxml decorator polib pillow psycopg2 idna python-dateutil psutil requests jinja2
If you are using Pipenv, you may need to add this to your Pipfile:
[packages]
python-dateutil = "*"
Related
This question already has answers here:
Need to Install PyOpenGL (Windows)
(1 answer)
PyOpenGL glutInit NullFunctionError
(14 answers)
Attempt to call an undefined function glutInit
(2 answers)
Closed 2 years ago.
I have a project when I need to do boolean operations with 3D models (CGS mainly), and I was trying to implement the example given on the library for python but it is not working. Seems like the code runs on OpenGL and the error comes from it instead of the example.
Anybody has an idea of how to make it work?
What am I missing?
Here is the error I get and the library link is below.
OpenGL.error.NullFunctionError: Attempt to call an undefined function
glutInit, check for bool(glutInit) before calling
Library link: https://github.com/timknip/pycsg
Example code
import sys
import os
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
sys.path.insert(0, os.getcwd())
from csg.core import CSG
from csg.geom import Vertex, Vector
from optparse import OptionParser
light_ambient = [0.3, 0.3, 0.3, 1.0]
light_diffuse = [0.7, 0.7, 0.7, 1.0] # Red diffuse light
light_position = [100.0, 100.0, 100.0, 0.0] # Infinite light location.
rot = 0.0
class TestRenderable(object):
def __init__(self, operation):
self.faces = []
self.normals = []
self.vertices = []
self.colors = []
self.vnormals = []
self.list = -1
a = CSG.cube()
b = CSG.cylinder(radius=0.5, start=[0., -2., 0.], end=[0., 2., 0.])
for p in a.polygons:
p.shared = [1.0, 0.0, 0.0, 1.0]
for p in b.polygons:
p.shared = [0.0, 1.0, 0.0, 1.0]
recursionlimit = sys.getrecursionlimit()
sys.setrecursionlimit(10000)
try:
if operation == 'subtract':
polygons = a.subtract(b).toPolygons()
elif operation == 'union':
polygons = a.union(b).toPolygons()
elif operation == 'intersect':
polygons = a.intersect(b).toPolygons()
else:
raise Exception('Unknown operation: \'%s\'' % operation)
except RuntimeError as e:
raise RuntimeError(e)
sys.setrecursionlimit(recursionlimit)
for polygon in polygons:
n = polygon.plane.normal
indices = []
for v in polygon.vertices:
pos = [v.pos.x, v.pos.y, v.pos.z]
if not pos in self.vertices:
self.vertices.append(pos)
self.vnormals.append([])
index = self.vertices.index(pos)
indices.append(index)
self.vnormals[index].append(v.normal)
self.faces.append(indices)
self.normals.append([n.x, n.y, n.z])
self.colors.append(polygon.shared)
# setup vertex-normals
ns = []
for vns in self.vnormals:
n = Vector(0.0, 0.0, 0.0)
for vn in vns:
n = n.plus(vn)
n = n.dividedBy(len(vns))
ns.append([a for a in n])
self.vnormals = ns
def render(self):
if self.list < 0:
self.list = glGenLists(1)
glNewList(self.list, GL_COMPILE)
for n, f in enumerate(self.faces):
glMaterialfv(GL_FRONT, GL_DIFFUSE, self.colors[n])
glMaterialfv(GL_FRONT, GL_SPECULAR, self.colors[n])
glMaterialf(GL_FRONT, GL_SHININESS, 50.0)
glColor4fv(self.colors[n])
glBegin(GL_POLYGON)
if self.colors[n][0] > 0:
glNormal3fv(self.normals[n])
for i in f:
if self.colors[n][1] > 0:
glNormal3fv(self.vnormals[i])
glVertex3fv(self.vertices[i])
glEnd()
glEndList()
glCallList(self.list)
renderable = None
def init():
# Enable a single OpenGL light.
glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient)
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse)
glLightfv(GL_LIGHT0, GL_POSITION, light_position)
glEnable(GL_LIGHT0);
glEnable(GL_LIGHTING);
# Use depth buffering for hidden surface elimination.
glEnable(GL_DEPTH_TEST);
# Setup the view of the cube.
glMatrixMode(GL_PROJECTION);
gluPerspective(40.0, 640./480., 1.0, 10.0);
glMatrixMode(GL_MODELVIEW);
gluLookAt(0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.)
def display():
global rot
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glPushMatrix()
glTranslatef(0.0, 0.0, -1.0);
glRotatef(rot, 1.0, 0.0, 0.0);
glRotatef(rot, 0.0, 0.0, 1.0);
rot += 0.1
renderable.render()
glPopMatrix()
glFlush()
glutSwapBuffers()
glutPostRedisplay()
if __name__ == '__main__':
parser = OptionParser()
parser.add_option('-o', '--operation', dest='operation',
type='str', default='subtract')
(options, args) = parser.parse_args()
renderable = TestRenderable(options.operation)
glutInit()
glutInitWindowSize(640,480)
glutCreateWindow("CSG Test")
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA)
glutDisplayFunc(display)
init()
glutMainLoop()
There is a issue when installing pyopengl with pip install pyopengl on Windows systems.
Go to Unofficial Windows Binaries for Python Extension Packages
Download a 32 bit or 64 bit package for PyOpenGL provides bindings to OpenGL, GLUT, and GLE
(e.g.
PyOpenGL‑3.1.5‑cp39‑cp39‑win_amd64.whl and
PyOpenGL_accelerate‑3.1.5‑cp39‑cp39‑win_amd64.whl)
Open Command Prompt (cmd.exe) as administrator. Change to the download directory and install the packages by pip install packagename.whl.
e.g:
pip install PyOpenGL‑3.1.5‑cp39‑cp39‑win_amd64.whl
and
pip install PyOpenGL_accelerate‑3.1.5‑cp39‑cp39‑win_amd64.whl
If the package is already installed, but doesn't work, then you have to ignore the currently installed package, by the option --ignore-installed:
pip install --ignore-installed PyOpenGL‑3.1.5‑cp39‑cp39‑win_amd64.whl
pip install --ignore-installed PyOpenGL_accelerate‑3.1.5‑cp39‑cp39‑win_amd64.whl
Is there a better or shorter way to write this code?
def business_role_code_to_name(x):
y = []
for position, code in enumerate(x):
if position == 0 and code == 1.0:
y.append("Owner")
elif position == 1 and code == 1.0:
y.append("Manager")
elif position == 2 and code == 1.0:
y.append("Employee")
elif position == 3 and code == 1.0:
y.append("Other")
return y
assert business_role_code_to_name([1.0, 1.0, 1.0, 0.0]) == ['Owner', 'Manager', 'Employee']
assert business_role_code_to_name([0.0, 1.0, 0.0, 1.0]) == ['Manager', 'Other']
I am new to programming, I think there is a better way to write this code. Thanks!
Try using:
def business_role_code_to_name(x):
y = []
d = {(0, 1): 'Owner', (1, 1): 'Manager', (2, 1): 'Employee', (3, 1): 'Other'}
for i in enumerate(x):
if d.get(i):
y.append(d[i])
return y
Use itertools.compress:
from itertools import compress
names = ['Owner', 'Manager', 'Employee', 'Other']
positions_0 = [1.0, 1.0, 1.0, 0.0]
positions_1 = [0.0, 1.0, 0.0, 1.0]
Output:
list(compress(names, positions_0))
# ['Owner', 'Manager', 'Employee']
list(compress(names, positions_1))
# ['Manager', 'Other']
The function business_role_code_to_name has the same logic as below
def business_role_code_to_name(x):
z = ['Owner', 'Manager', 'Employee' ,'Other']
y = [z[position] for position, code in enumerate(x) if code==1.0]
return y
You might use zip for that task following way:
roles = ["Owner","Manager","Employee","Other"]
code1 = [1.0, 1.0, 1.0, 0.0]
code2 = [0.0, 1.0, 0.0, 1.0]
def decode_role(rolecode):
return [role for code,role in zip(rolecode,roles) if code==1.0]
print(decode_role(code1)) # ['Owner', 'Manager', 'Employee']
print(decode_role(code2)) # ['Manager', 'Other']
I have written an example with error handling:
Function:
def business_role_code_to_name(x):
y = []
positions = {0: "Owner", 1: "Manager", 2: "Employee", 3: "Other"}
for position, code in enumerate(x):
if code != 1.0:
continue
try:
y.append(positions[position])
except KeyError as key_err:
print("{} is a wrong index.".format(position))
raise key_err
return y
Test:
print(business_role_code_to_name([1.0, 1.0, 1.0, 0.0]))
print(business_role_code_to_name([0.0, 1.0, 0.0, 1.0]))
print(business_role_code_to_name([0.0, 1.0, 0.0, 1.0, 1.0]))
Output:
>>> python3 test.py
['Owner', 'Manager', 'Employee']
['Manager', 'Other']
4 is a wrong index.
Traceback (most recent call last):
File "test.py", line 21, in <module>
print(business_role_code_to_name([0.0, 1.0, 0.0, 1.0, 1.0]))
File "test.py", line 11, in business_role_code_to_name
raise key_err
File "test.py", line 8, in business_role_code_to_name
y.append(positions[position])
KeyError: 4
You can do it like this without foor loops:
roles = ('Owner', 'Manager', 'Employee', 'Other')
def business_role_code_to_name(x):
positions = filter(lambda k: x[k] == 1.0, range(len(x)))
return list(map(roles.__getitem__, positions))
I'm very new to QuantLib python package and I've been trying to run and understand this python written code for the Calibration of Black Karasinski model but I have problem on the line ql.CalibrationHelper.RelativePriceError. I'm always getting the error message: AttributeError: 'function' object has no attribute 'RelativePriceError'.
Please anyone with idea on what is wrong?
import QuantLib as ql
from collections import namedtuple
import math
displacement = 0.
voltype = ql.Normal
def create_swaption_helpers(data, index, term_structure, engine):
nominal = 1.0
swaptions = [ql.SwaptionHelper(ql.Period(swap.start, ql.Years),
ql.Period(swap.length, ql.Years),
ql.QuoteHandle(ql.SimpleQuote(swap.volatility)),
index, index.tenor(),
index.dayCounter(), index.dayCounter(),
term_structure,
ql.CalibrationHelper.RelativePriceError,
ql.nullDouble(),
nominal,
ql.ShiftedLognormal,
displacement) for swap in data]
for swap in swaptions:
swap.setPricingEngine(engine)
return swaptions
def calibration_report(swaptions, data):
print ("-"*82)
print ("%15s %15s %15s %15s %15s" %
"Model Price", "Market Price", "Implied Vol", "Market Vol", "RelError")
print ("-"*82)
cum_err = 0.0
for i, s in enumerate(swaptions):
model_price = s.modelValue()
market_vol = data[i].volatility
black_price = s.blackPrice(market_vol)
rel_error = model_price/black_price - 1.0
implied_vol = s.impliedVolatility(model_price,
1e-5, 50, 0.0, 0.50)
rel_error2 = implied_vol/market_vol-1.0
cum_err += rel_error2*rel_error2
print ("%15.5f %15.5f %15.5f %15.5f %15.5f" %
model_price, black_price, implied_vol, market_vol, rel_error)
print ("-"*82)
print ("Cumulative Error : %15.5f" % math.sqrt(cum_err))
today = ql.Date(15, ql.February, 2002);
settlement= ql.Date(19, ql.February, 2002);
term_structure = ql.YieldTermStructureHandle(
ql.FlatForward(settlement,0.04875825,ql.Actual365Fixed())
)
index = ql.Euribor1Y(term_structure)
CalibrationData = namedtuple("CalibrationData",
"start, length, volatility")
data = [CalibrationData(1, 5, 0.1148),
CalibrationData(2, 4, 0.1108),
CalibrationData(3, 3, 0.1070),
CalibrationData(4, 2, 0.1021),
CalibrationData(5, 1, 0.1000 )]
model = ql.BlackKarasinski(term_structure)
engine = ql.TreeSwaptionEngine(model, 100)
swaptions = create_swaption_helpers(data, index, term_structure, engine)
optimization_method = ql.LevenbergMarquardt(1.0e-8,1.0e-8,1.0e-8)
end_criteria = ql.EndCriteria(10000, 100, 1e-6, 1e-8, 1e-8)
model.calibrate(swaptions, optimization_method, end_criteria)
This is a problem in the package. It comes from a class in the underlying C++ library being renamed. The package tried to provide an alias for backwards compatibility, but it didn't work.
To work around it, use ql.BlackCalibrationHelper.RelativePriceError instead (i.e., the new name of the class).
I change this code to work in persian. My code returns:
Key: Text is too short to analyze Text:
and doesn't return key and decrypt text. Is it anything wrong with uppercase or ascii in persian text? What can I do?
# -*- coding: utf-8 -*-
from string import uppercase
from operator import itemgetter
def vigenere_decrypt(target_freqs, input):
nchars = len(uppercase)
ordA = ord(u"ا")
sorted_targets = sorted(target_freqs)
def frequency(input):
result = [[c, 0.0] for c in uppercase]
for c in input:
result[c - ordA][1] += 1
return result
def correlation(input):
result = 0.0
freq = frequency(input)
freq.sort(key=itemgetter(1))
for i, f in enumerate(freq):
result += f[1] * sorted_targets[i]
return result
cleaned = [ord(c) for c in input.upper() if c.isupper()]
best_len = 0
best_corr = -100.0
# Assume that if there are less than 20 characters
# per column, the key's too long to guess
for i in xrange(2, len(cleaned) // 20):
pieces = [[] for _ in xrange(i)]
for j, c in enumerate(cleaned):
pieces[j % i].append(c)
# The correlation seems to increase for smaller
# pieces/longer keys, so weigh against them a little
corr = -0.5 * i + sum(correlation(p) for p in pieces)
if corr > best_corr:
best_len = i
best_corr = corr
if best_len == 0:
return ("Text is too short to analyze", "")
pieces = [[] for _ in xrange(best_len)]
for i, c in enumerate(cleaned):
pieces[i % best_len].append(c)
freqs = [frequency(p) for p in pieces]
key = ""
for fr in freqs:
fr.sort(key=itemgetter(1), reverse=True)
m = 0
max_corr = 0.0
for j in xrange(nchars):
corr = 0.0
c = ordA + j
for frc in fr:
d = (ord(frc[0]) - c + nchars) % nchars
corr += frc[1] * target_freqs[d]
if corr > max_corr:
m = j
max_corr = corr
key += chr(m + ordA)
r = (chr((c - ord(key[i % best_len]) + nchars) % nchars + ordA)
for i, c in enumerate(cleaned))
return (key, "".join(r))
def main():
encoded = " پهيتش غعهدد ذصلدي هزفضر کنهرظ ضذکاح يصتمد "
english_frequences = [
14, 4.2, 0.7, 5.2, 0.1, 1.2, 0.4,
1, 1.4, 7.5, 0.1, 8.5, 2.1, 0.1,
3.3, 2.6, 0.7, 0.3, 0.6, 0.2, 1.5,
0.2, 1.6, 1.2, 3, 1.7, 2.7, 5.7, 7.1, 6, 5.7, 9.1]
(key, decoded) = vigenere_decrypt(english_frequences, encoded)
print "Key:", key
print "\nText:", decoded
main()
Hi i'm using the python and odbc database i.e Microsoft access. I'm getting the output like
(u'EXPANDx TB', 12.0, 10.0, 11.0, 13.0, 0.0, 46.0)
(u'EXPANDx TB & GFATM', 1.0, 1.0, 0.0, 1.0, 0.0, 3.0)
(u'EXPANDx TB & NRHM', 0.0, 0.0, 1.0, 0.0, 0.0, 1.0)
(u'GFATM', 1.0, 1.0, 0.0, 0.0, 0.0, 2.0)
(u'WHO', 3.0, 7.0, 3.0, 5.0, 0.0, 18.0)
(u'GFATM & EXPANDx TB', 1.0, 0.0, 0.0, 0.0, 0.0, 1.0)
the extra term "u" is displaying. I also used the join function but getting the error like
print ",".join(table1)
TypeError: sequence item 1: expected string or Unicode, float found
please help me out with this. Thanks in advance.
#!/usr/bin/python
import pyodbc
db_file = r'''C:\Users\Basavaraj\Documents\C&DST.accdb'''
user = ''
password = ''
odbc_conn_str = 'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=%s;UID=%s;PWD=%s' % \
(db_file, user, password)
conn= pyodbc.connect(odbc_conn_str)
#for row in cursor.fetchall():
# print row[2]
try:
cursor = conn.cursor()
cursor.execute("select * from Table1")
for table1 in cursor.fetchall():
print ",".join(table1)
finally:
conn.close()
`
Just convert each item to string.
print ",".join(str(i) for i in table1)
If you want to keep the unicode items as is, then :
print ",".join(str(i) if not isinstance(i, unicode) else i for i in table1)