how to extract file path from QFileSystemModel? - pyqt4

def nukeScriptFolder(self, index = QModelIndex()):
index = self.dirmodel.index(QDir.currentPath())
fileInfo = QtCore.QFileInfo(self.dirmodel.fileInfo(index))
#print fileInfo.fileName()
#path = self.dirmodel.fileinfo(index).absoluteFilePath()
self.fileView.setRootIndex(filemodel.setRootPath(path))
When I execute the above code I get the following error
path_index = self.dirmodel.index(QDir.currentPath()).toString()
TypeError: 'sip.methoddescriptor' object is not callable

Related

How to read from a written file?

I need to use changed text document (from a function changed_document) in a function called lines. But I cannot just simply use the changed list or string. It shows me an error that "AttributeError: 'str' object has no attribute 'readlines'". So I've tried to write the changed text in to a new text file and then read it to use in the line function. But it doesn't work. I cannot read that newly written text file. It prints just empty lines.
def reading():
doc = open("C:/Users/s.txt", "r", encoding= 'utf-8')
docu = doc
return docu
def longest_word_place(document):
words = document.read().split()
i = 0
max = 0
max_place = 0
for i in range(len(words)):
if len(words[i]) > max:
max = len(words[i])
max_place = i
return max_place
def changed_document (document):
list = []
for line in document:
for symbol in line:
if symbol.isnumeric():
symbol = ' '
if symbol in "#,.;«\³][:¡|>^' '<?+=_-)(*&^%$£!`":
symbol = ' '
list.append(symbol)
document_changed =''.join([str(item) for item in list])
return document_changed
def lines(document):
lines = document.readlines()
max_word = ''
max_line = 0
for line_index, every_line in enumerate(lines, 1):
line_words = every_line.strip().split()
for each_word in line_words:
if len(each_word) > len(max_word):
max_word = each_word
max_line = line_index
print(f"{max_word = }, {max_line = }")
document = reading()
ch_dok = changed_document(document)
text_file = open("C:/Users/changed_doc.txt", "w+", encoding= 'utf-8')
text_file.write(ch_dok)
text_file.close
doc1 = open("C:/Users/changed_doc.txt", "r", encoding= 'utf-8')
for line1 in doc1:
print(line1)
In "text_file.close" you missed the parenthesis, so the file is not closed (just the function itself is returned, not called).
Perhaps this is the issue..?

Accessing local variable within same class python

I tried to create a dataframe from excel files in remote desktop using Paramiko, but I failed to call setPath() to writeDataframe() and got this error
TypeError: writeDataframe() takes 1 positional argument but 2 were given
Here is my code :
class remoteConnection:
def __init__(self,hostname, username, password, path):
self.hostname = hostname
self.username = username
self.password = password
self.path = path
def connectRemote(self):
client = SSHClient()
client.set_missing_host_key_policy(AutoAddPolicy())
client.connect(hostname=self.hostname,
username=self.username,
password=self.password,
look_for_keys=False,
allow_agent=False)
sftp_handle = client.open_sftp()
sftp_handle.chdir('.' + '/' + self.path)
base_dir = sftp_handle.getcwd()
return sftp_handle, base_dir
def setPath(self, *pattern):
current_sftp_handle , current_dir = self.connectRemote()
for i in pattern :
current_sftp_handle.chdir(current_dir+'/'+str(i)+'/')
updated_dir = current_sftp_handle.getcwd()
return current_sftp_handle
def writeDataframe(self):
updated_sftp_handle = self.setPath()
filename = [file for file in updated_sftp_handle.listdir()]
appended_data = pd.DataFrame()
for file in filename:
f = updated_dir.open(file)
temp_df = pd.read_excel(f)
temp_df['Filename'] = file
utime = f.stat().st_mtime
temp_df['Date modified'] = datetime.fromtimestamp(utime)
appended_data = appended_data.append(temp_df)
return appended_data
I called my function like this:
hostname='xxx.xxx.x.xxx'
username='username'
password1='XXXXXXXXXXXX'
path1 = '/Documents/datasets'
initClass = remoteConnection(hostname, username, password1, path1)
connection = initClass.connectRemote()
a = ['SOURCE A', 'SOURCE B']
for i in a:
my_obj = initClass.setPath(i)
print(my_obj)
dg = initClass.writeDataframe(my_obj)
Has anyone got any advice? Thanks
Obviously you forgot to declare the argument or are passing an unneded argument:
Oprion 1: declare the argument:
def writeDataframe(self, arg):
Option 2: call the method without the arg:
dg = initClass.writeDataframe()

object has no attribute error with python3

I have a error when trying to call calculate_similarity2 function which in in DocSim.py file from my notebook.
The error message is : 'DocSim' object has no attribute 'calculate_similarity2'
Here the content of my docsim File :
import numpy as np
class DocSim(object):
def __init__(self, w2v_model , stopwords=[]):
self.w2v_model = w2v_model
self.stopwords = stopwords
def vectorize(self, doc):
"""Identify the vector values for each word in the given document"""
doc = doc.lower()
words = [w for w in doc.split(" ") if w not in self.stopwords]
word_vecs = []
for word in words:
try:
vec = self.w2v_model[word]
word_vecs.append(vec)
except KeyError:
# Ignore, if the word doesn't exist in the vocabulary
pass
# Assuming that document vector is the mean of all the word vectors
# PS: There are other & better ways to do it.
vector = np.mean(word_vecs, axis=0)
return vector
def _cosine_sim(self, vecA, vecB):
"""Find the cosine similarity distance between two vectors."""
csim = np.dot(vecA, vecB) / (np.linalg.norm(vecA) * np.linalg.norm(vecB))
if np.isnan(np.sum(csim)):
return 0
return csim
def calculate_similarity(self, source_doc, target_docs=[], threshold=0):
"""Calculates & returns similarity scores between given source document & all
the target documents."""
if isinstance(target_docs, str):
target_docs = [target_docs]
source_vec = self.vectorize(source_doc)
results = []
for doc in target_docs:
target_vec = self.vectorize(doc)
sim_score = self._cosine_sim(source_vec, target_vec)
if sim_score > threshold:
results.append({
'score' : sim_score,
'sentence' : doc
})
# Sort results by score in desc order
results.sort(key=lambda k : k['score'] , reverse=True)
return results
def calculate_similarity2(self, source_doc=[], target_docs=[], threshold=0):
"""Calculates & returns similarity scores between given source document & all the target documents."""
if isinstance(source_doc, str):
target_docs = [source_doc]
if isinstance(target_docs, str):
target_docs = [target_docs]
#source_vec = self.vectorize(source_doc)
results = []
for doc in source_doc:
source_vec = self.vectorize(doc)
for doc1 in target_docs:
target_vec = self.vectorize(doc)
sim_score = self._cosine_sim(source_vec, target_vec)
if sim_score > threshold:
results.append({
'score' : sim_score,
'source sentence' : doc,
'target sentence' : doc1
})
# Sort results by score in desc order
results.sort(key=lambda k : k['score'] , reverse=True)
return results
here in instruction code when i try to call the fucntion :
To create DocSim Object
ds = DocSim(word2vec_model,stopwords=stopwords)
sim_scores = ds.calculate_similarity2(source_doc, target_docs)
the error message is :
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-54-bb0bd1e0e0ad> in <module>()
----> 1 sim_scores = ds.calculate_similarity2(source_doc, target_docs)
AttributeError: 'DocSim' object has no attribute 'calculate_similarity2'
i don't undersantand how to resolve this problem.
I can access to all function except calculate_similarity2
Can you help me please?
thanks
You have defined the calculate_similarity2 function inside the __init__ scope. Try getting it out of there

How to load from Json?

I'am trying to get the information from the web api with Python 3 but it gives me an error. That's my code:
import json, urllib.request, requests
def findLocation():
"""returns latlng location value in the form of a list."""
send_url = 'http://freegeoip.net/json'
r = requests.get(send_url)
j = json.loads(r.text)
lat = j['latitude']
lon = j['longitude']
return lat, lon
location = findLocation()
print(findLocation()[0])
print(findLocation()[1])
def readJsonUrl(url):
"""reads the Json returned by the google api and converts it into a format
that can be used in python."""
page = urllib.request.urlopen(url)
data_bytes = page.read()
data_str = data_bytes.decode("utf-8")
page.close()
return data_str
search =readJsonUrl("https://maps.googleapis.com/maps/api/place/textsearch/json?query=indian+restaurantsin+Coventry&location=52.4066,-1.5122&key=AIzaSyCI8n1sI4CDRnsYo3hB_oH1trfxbt2IEaw")
print(search['website'])
Error:
Traceback (most recent call last):
File "google api.py", line 28, in <module>
print(search['website'])
TypeError: string indices must be integers
Any help is appreciated.
The function you are using readJsonUrl() returns a string not JSON. Therefore, when you try search['website'] it fails because the indices on a string can only be integers.
Try parsing the string value to a JSON object. To do this you can try the accepted answer here Convert string to JSON using Python
data_str is string ( not dict format ) You should convert data_str to dict! just add this line to your code : convert_to_dict = json.loads(data_str). then return convert_to_dict ... and done.
Try this :
import json, urllib.request, requests
def findLocation():
send_url = 'http://freegeoip.net/json'
r = requests.get(send_url)
j = json.loads(r.text)
lat = j['latitude']
lon = j['longitude']
return lat, lon
location = findLocation()
print(findLocation()[0])
print(findLocation()[1])
def readJsonUrl(url):
page = urllib.request.urlopen(url)
data_bytes = page.read()
data_str = data_bytes.decode("utf-8")
page.close()
convert_to_dict = json.loads(data_str) # new line
return convert_to_dict # updated
search = readJsonUrl("https://maps.googleapis.com/maps/api/place/textsearch/json?query=indian+restaurantsin+Coventry&location=52.4066,-1.5122&key=AIzaSyCI8n1sI4CDRnsYo3hB_oH1trfxbt2IEaw")
print(search['your_key']) # now you can call your keys
The reason for for the TypeError: string indices must be integers is because your readJsonUrl function is returning str object instead of dict object. Using the json.loads function can help you transfer the str object to dict object.
You can try something like the following:
def readJsonUrl(url):
with (urllib.request.urlopen(url)) as page:
raw = page.read().decode("utf-8")
json_data = json.loads(raw)
return json_data
search =readJsonUrl("https://maps.googleapis.com/maps/api/place/textsearch/json?query=indian+restaurantsin+Coventry&location=52.4066,-1.5122&key=AIzaSyCI8n1sI4CDRnsYo3hB_oH1trfxbt2IEaw")
print(search['results'])
Hope it helps.

struct.pack in Python3 got struct.error: required argument is not an integer

I'm doing a zipping func of this:
open_file = open(file_path,'rb')
open_save = open(save_path,'wb+')
try:
open_read = open_file.read()
data = zip_data(open_read)
head_xis = b'XIS'
head_version = bytes(0)
head_type1 = bytes(1)
head_type2 = bytes(1)
head_en_type = bytes(0)
head_com_type = bytes(1)
head_sour_len = len(open_read)
# try:
md5 = hashlib.md5()
md5.update(open_read)
head_md5 = md5.digest()
print("byteeeeee")
# except:
# head_md5 = None
randoms = str(uuid.uuid1()).split('-')[0]
head_random = bytes(randoms,encoding = "utf-8")
print(head_md5)
print(head_random)
head_resour_len= len(data)
print(type(head_xis))
print(type(head_version))
print(type(head_type1))
print(type(head_type2))
print(type(head_en_type))
print(type(head_com_type))
print(type(head_sour_len))
print(type(head_md5))
print(type(head_random))
print(type(head_resour_len))
head = struct.pack('3sBBBBBI16s8sI',
head_xis,
head_version,
head_type1,
head_type2,
head_en_type,
head_com_type,
head_sour_len,
head_md5,
head_random,
head_resour_len
)
open_save.write(head)
# except Exception as e:
# print("eeeee" + str(e))
# return False,str(e)
# else:
# open_save.write(data)
# return True,''
finally:
open_file.close()
open_save.close()
and it shows exception and print like below:
byteeeeee
b'\xf9\xf4\xf2\xcb\xbfM\x11\xb5\xeeNP/\x02H\xebK'
b'f9f33502'
class 'bytes'
class 'bytes'
class 'bytes'
class 'bytes'
class 'bytes'
class 'bytes'
class 'int'
class 'bytes'
class 'bytes'
class 'int'
Traceback (most recent call last):
File "entrance.py", line 52, in startProcess
Helper.processCombine(self.selectedVer,False)
File "/Users/mapzchen/myShell/qtPro/fastColuaco/Helper.py", line 86, in processCombine
itemConf.get(version,suffix),True,True)
File "/Users/mapzchen/myShell/qtPro/fastColuaco/coluaco.py", line 514, in process
compress(build_dir,zip_dir,filter_file)
File "/Users/mapzchen/myShell/qtPro/fastColuaco/coluaco.py", line 400, in compress
zfile = zip_file(src_file_path,save_path)
File "/Users/mapzchen/myShell/qtPro/fastColuaco/coluaco.py", line 131, in zip_file
head_resour_len
struct.error: required argument is not an integer
I have tried to print types of arguments,
and it seems to fit 3sBBBBBI16s8sI correctly
I'm confused by what arg that performs this exception
In structure formating string "B" for bytes need variable type 'int', that is main problem. So instead of head_type1 = bytes(1) use head_type1 = 1
Here given below code gives same error.
Problem:
n = bytes(2)
x = struct.pack("B", n)
Solution:
n = 2
x = struct.pack("B", n)
Suggestion:
Use Byte Orders like '=', while dealing with integers like 'I'.

Resources