Error: 'str ' object does not support item assignment python
dict=['A', 'a','B', 'b','C', 'c','D', 'd','E', 'e','F', 'f','G', 'g','H', 'h','I', 'i','J', 'j','K', 'k','L', 'l','M', 'm','N', 'n','P', 'o','P', 'p','Q', 'q','R', 'r','S', 's','T', 't','U', 'u','V', 'v','W', 'w','X', 'x','Y', 'y','Z' 'z']
def cript(s):
for i in range(0,len(s)):
a=dict.index(s[i])
if a<26:
s[i]=dict[a+26]
else:
s[i]=dict[a-26]
return s
print cript('Hello')
Error line 6
s[i]= dict[a+26]
TypeError: 'str' object does not support item assignment python
Python does not allow you to swap out characters in a string for another one; strings are immutable. What you'll need to do is create a totally different string and return that instead.
dict=['A', 'a','B', 'b','C', 'c','D', 'd','E', 'e','F', 'f','G', 'g','H', 'h','I', 'i','J', 'j','K', 'k','L', 'l','M', 'm','N', 'n','P', 'o','P', 'p','Q', 'q','R', 'r','S', 's','T', 't','U', 'u','V', 'v','W', 'w','X', 'x','Y', 'y','Z' 'z']
def cript(s):
crypt_s = ""
for i in range(0,len(s)):
a=dict.index(s[i])
if a<26:
crypt_s += dict[a+26]
else:
crypt_s += dict[a-26]
return crypt_s
print cript('Hello')
Of course, there may be other issues with the code, but that will solve that specific error message.
Strings are immutable objects, meaning they can't be modified in place (you'd have to return a new string and reassign it).
s[i] = dict[a + 26]
is trying to reassign a value in the string
Here is an easier to see example
>>> astring = "Hello"
>>> astring[0] = "a"
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
astring[0] = "a"
TypeError: 'str' object does not support item assignment
def game():
list = ["pomme", "anniversaire", "table", "travail", "amies", "enfants"]
ran = random.randint(0, (len(list)-1)/2)
mot = list[ran]
length = len(mot)
for x in range(0, length-1):
if length % 2 ==0:
a = int(random.randint(-length/2, length/2))
else:
a = int(random.randint(-(length-1)/2, (length-1)/2))
mot[x] = mot[x+a]
Related
I'm trying to use babelNet instead of wordnet because I have special combined words from the computer science domain, my code is to find similarities for a list of topics (lst).
code:
from babelnetpy.babelnet import BabelNet
bn = BabelNet("")
lst = ['artificial_intelligence', "real_time", 'Big_data', "Healthcare",'Fuzzy_logic']
def get_bn_main_sense(synsetid):
"""
get main sense
"""
return bn.getSynsets(synsetid)[0].mainSense
get_bn_main_sense('bn:03890554n')
def get_synset(a_list):
synset_list = []
for word in a_list:
a = bn.getSynset_Ids(word, "en")[:1] #The index is to ensure each word gets assigned 1st synset only
synset_list.append(a)
return synset_list
lst_synsets = get_synset(lst)
def bn_syns(given_list):
synset_bn = []
for word in given_list:
synset_bn.append("bn.[%s]" % word)
return synset_bn
lst_s_bn = bn_syns(lst_synsets)
def lower(list):
new_list = []
for word in list:
new_list.append(word.lower())
return new_list
lower_is = lower(lst_s_bn)
def clean(a_list):
new_list = []
for word in a_list:
b = word.replace("[", "").replace("]", "").replace("bn.synset", "").replace("(", "").replace(")", "").replace("'", "")
new_list.append(b)
return new_list
clean_is = clean(lower_is)
# id of the synset you want to retrieve
artificial_intelligence_Ids = bn.getSynset_Ids("artificial_intelligence", "en")
artificial_intelligence=artificial_intelligence_Ids[0]
real_time_Ids = bn.getSynset_Ids("real_time", "en")
real_time=real_time_Ids[0]
Big_data_Ids = bn.getSynset_Ids("Big_data", "en")
Big_data=Big_data_Ids[0]
Healthcare_Ids = bn.getSynset_Ids("Healthcare", "en")
Healthcare=Healthcare_Ids[0]
Fuzzy_logic_Ids = bn.getSynset_Ids("Fuzzy_logic", "en")
Fuzzy_logic=Fuzzy_logic_Ids[0]
#is_variables
artificial_Intelligence_syn = get_bn_main_sense('bn:03890554n')
real_time_syn = get_bn_main_sense('bn:01258457n')
Big_data_syn = get_bn_main_sense('bn:02063206n')
Healthcare_syn = get_bn_main_sense('bn:00043361n')
Fuzzy_logic_syn = get_bn_main_sense('bn:15130487n')
is_variables = [artificial_Intelligence_syn, real_time_syn, Big_data_syn, Healthcare_syn,Fuzzy_logic_syn]
# wup similarity
def similarity(list1, list2):
sim_dict = {}
for syn in list1:
for sin in list2:
sim = (syn).wup_similarity(sin)
if sim >= 0.5:
sim_dict.update({(syn, sin): sim})
return sim_dict
b_s = similarity(is_variables, is_variables)
I get the error "AttributeError: 'str' object has no attribute 'wup_similarity'" when I try to run this code to find a semantic similarity for this list (last) !!!
. any suggestions or hints are highly appreciated.
The returned values of the function get_bn_main_sense are of type string. str doesn't have any method named wup_similarity. mainSense is of type string:
>>> type(bn.getSynsets('bn:03890554n')[0].mainSense)
<class 'str'>
I couldn't find any object or class with this method or algorithm in the babelnetpy library.
NLTK library does have this method but uses Wordnet. Maybe you have confused these two libraries.
In my code, I call this function ReVerseShiftRowMK2, and the appending function would not work. I then try to print the List to try and debug it, and suddenly it works? However, it is still giving me ERROR(TypeError: 'function' object is not subscriptable).
I think it have something to do with <function reVersedMixCol at 0x000002392B1100D8>?
Here is the console
HERE1 ['4f', '4f', '86', '16', '11', '49', '07', 'ce', '08', '8b', '4f', 'd3', '44', 'db', '50', 'e8']
HERE2 ce
HERE1 <function reVersedMixCol at 0x000002142F820168>
Traceback (most recent call last):
File "c:/Users/me the commie/Documents/!School/Computer science/New folder/AES encryption.py", line 806, in <module>
print(DESCRYSubAESHex(S, KeyScheldule(Key_HEX_list, 10)))
File "c:/Users/me the commie/Documents/!School/Computer science/New folder/AES encryption.py", line 779, in DESCRYSubAESHex
SubHex1 = ReVerseShiftRowMK2(SubHex1)
File "c:/Users/me the commie/Documents/!School/Computer science/New folder/AES encryption.py", line 490, in ReVerseShiftRowMK2
print(("HERE2 " + str(Box4x4[7])))
TypeError: 'function' object is not subscriptable
and here is the function
def ReVerseShiftRowMK2(Box4x4):
print("HERE1 " + str(Box4x4))
Row1 = []
Row2 = []
Row3 = []
Row4 = []
print(("HERE2 " + str(Box4x4[7])))
for a in range(4):
Row1.append(Box4x4[a + 0])
Row2.append(Box4x4[a + 4])
Row3.append(Box4x4[a + 8])
Row4.append(Box4x4[a + 12])
####### more code #############
This function is called in:
def DESCRYSubAESHex(SubHex1, FullKey):
#print(SubHex1)
#print(FullKey)
for a in range(16):
#print(SubHex1[a])
#print(FullKey[0][a])
SubHex1[a] = xor_strings(SubHex1[a],FullKey[len(FullKey) - 1][a])
for a in range(len(FullKey) - 2): # 0 to 13
#print(SubHex1)
SubHex1 = ReVerseShiftRowMK2(SubHex1)
SubHex1 = reVeredSBox(SubHex1)
for b in range(16):
SubHex1[b] = xor_strings(SubHex1[b],FullKey[(len(FullKey) - 2) - a][b])
SubHex1 = reVersedMixCol
SubHex1 = ReVerseShiftRowMK2(SubHex1)
SubHex1 = reVeredSBox(SubHex1)
for b in range(16):
SubHex1[b] = xor_strings(SubHex1[b],FullKey[0][b])
return SubHex1
print(DESCRYSubAESHex(S, A))
S is a 16index array
A is a 2d array consisting of 10 by 16
([][][][][][][][][][][][][][][][])
([][][][][][][][][][][][][][][][])
([][][][][][][][][][][][][][][][])
...
down to 10
I think what's happening is this function is being run multiple times. The first time it is run, you passed in the right thing, an array. So it correctly prints.
The second time, presumably this line: SubHex1 = ReVerseShiftRowMK2(SubHex1), you passed in a function. So that's why this was printed:
<function reVersedMixCol at 0x000002392B1100D8>
because of this line:
print(Box4x4)
Then, when it got to this line:
print(Box4x4[7])
It errored out. So I would look into that SubHex variable from above.
And like Inyoung Kim said, this SubHex variable is probably a reference to the ReVerseMixCol function
in function declaration def DESCRYSubAESHex(SubHex1, FullKey)
for b in range(16):
SubHex1[b] = xor_strings(SubHex1[b],FullKey[(len(FullKey) - 2) - a][b])
SubHex1 = reVersedMixCol
SubHex1 = ReVerseShiftRowMK2(SubHex1)
SubHex1 = reVeredSBox(SubHex1)
you assigned reVersedMixCol to the variable SubHex1
then you passed SubHex1 to ReverseShiftRowMK2
Inside ReverseShiftRowMK2, you are trying to access index 7 of Box4x4 which actually contains a function. This is why error TypeError: 'function' object is not subscriptable is thrown. Meaning you can't index on to functions
I'm currently coding a TF-IDF program in python. I followed a code from this, however it's not working.
The problem is 'int' object is not iterable.
Traceback (most recent call last):
File "C:/Users/Try Arie/PycharmProjects/TF-IDF/tf-idf.py", line 106, in <module>
TF_scores = computeTF(doc_info, freqDict_list)
File "C:/Users/Try Arie/PycharmProjects/TF-IDF/tf-idf.py", line 67, in computeTF
for k in tempDict['freq_dict']:
TypeError: 'int' object is not iterable
I haven't tried anything yet because I just followed the code in the link.
def create_freq_dict(sents):
i = 0
freqDict_list = []
for sent in sents:
i += 1
freq_dict = {}
words = word_tokenize(sent)
for word in words:
word.lower()
if word in freq_dict:
freq_dict[word] += 1
else:
freq_dict = 1
temp = {'doc_id': i, 'freq_dict': freq_dict}
freqDict_list.append(temp)
return freqDict_list
def computeTF(doc_info, freqDict_list):
TF_scores = []
for tempDict in freqDict_list:
id = tempDict['doc_id']
for k in tempDict['freq_dict']:
temp = {'doc_id': id,
'TF_score': tempDict['freq_dict'][k]/doc_info[id-1]['doc_length'],
'key': k}
TF_scores.append(temp)
return TF_scores
I expect the output to be like this:
Update this line
for k in range(tempDict['freq_dict']):
I'm using python 3.2.2 on windows 7.This is part of my code.it reads from an excel file .But when I run the code it just prints from 0 to 10 and gives" TypeError: 'float' object is not iterable".
Thanks for any help!
pages = [i for i in range(0,19634)]
for page in pages:
x=df.loc[page,["id"]]
x=x.values
x=str(x)[2:-2]
text=df.loc[page,["rev"]]
def remove_punct(text):
text=''.join([ch.lower() for ch in text if ch not in exclude])
tokens = re.split('\W+', text)
tex = " ".join([wn.lemmatize(word) for word in tokens if word not in stopword])
removetable = str.maketrans('', '', '1234567890')
out_list = [s.translate(removetable) for s in tokens1]
str_list = list(filter(None,out_list))
line = [i for i in str_list if len(i) > 1]
return line
s=df.loc[page,["rev"]].apply(lambda x:remove_punct(x))
with open('FileNamex.csv', 'a', encoding="utf-8") as f:
s.to_csv(f, header=False)
print(s)
this is the Error
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-54-c71f66bdaca6> in <module>()
33 return line
34
---> 35 s=df.loc[page,["rev"]].apply(lambda x:remove_punct(x))
36
37 with open('FileNamex.csv', 'a', encoding="utf-8") as f:
C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\series.py in apply(self, func, convert_dtype, args, **kwds)
3190 else:
3191 values = self.astype(object).values
-> 3192 mapped = lib.map_infer(values, f, convert=convert_dtype)
3193
3194 if len(mapped) and isinstance(mapped[0], Series):
pandas/_libs/src\inference.pyx in pandas._libs.lib.map_infer()
<ipython-input-54-c71f66bdaca6> in <lambda>(x)
33 return line
34
---> 35 s=df.loc[page,["rev"]].apply(lambda x:remove_punct(x))
36
37 with open('FileNamex.csv', 'a', encoding="utf-8") as f:
<ipython-input-54-c71f66bdaca6> in remove_punct(text)
22
23 def remove_punct(text):
---> 24 text=''.join([ch.lower() for ch in text if ch not in exclude])
25 tokens = re.split('\W+', text)
26 tex = " ".join([wn.lemmatize(word) for word in tokens if word not in stopword])
TypeError: 'float' object is not iterable
Thanks for any help!
You are trying to apply a function that iterates text (whatever it is) - and ou call it using a float value.
floats can not be iterated. You can use text = str(text) to convert any input to text first - but looking at your code I hesitate to say that would make sense.
You can check if you are handling a float like this:
def remove_punct(text):
if isinstance(text,float):
pass # do something sensible with floats here
return # something sensible
text=''.join([ch.lower() for ch in text if ch not in exclude])
tokens = re.split('\W+', text)
tex = " ".join([wn.lemmatize(word) for word in tokens if word not in stopword])
removetable = str.maketrans('', '', '1234567890')
out_list = [s.translate(removetable) for s in tokens1]
str_list = list(filter(None,out_list))
line = [i for i in str_list if len(i) > 1]
return line
You can either tackle float via isinstance or get inspiration from
In Python, how do I determine if an object is iterable? on how to detect if you provide any iterable. You need to handle non-iterables differently.
How to debug "NameError: global name 'X' is not defined" in Python? I am pretty much new in Python. I am using jupyter_notebook with Python 2.7 to execute code. I am facing following error.
My code:
logFile = "NASAlog.txt"
def parseLogs():
parsed_logs=(sc
.textFile(logFile)
.map(parseApacheLogLine)
.cache())
access_logs = (parsed_logs
.filter(lambda s: s[1] == 1)
.map(lambda s: s[0])
.cache())
failed_logs = (parsed_logs
.filter(lambda s: s[1] == 0)
.map(lambda s: s[0]))
failed_logs_count = failed_logs.count()
if failed_logs_count > 0:
print 'Number of invalid logline: %d' % failed_logs.count()
for line in failed_logs.take(20):
print 'Invalid logline: %s' % line
print 'Read %d lines, successfully parsed %d lines, failed to parse %d lines' % (parsed_logs.count(), access_logs.count(), failed_logs.count())
return parsed_logs, access_logs, failed_logs
parsed_logs, access_logs, failed_logs = parseLogs()
ERROR
> NameError Traceback (most recent call last)
> <ipython-input-18-b365aa793252> in <module>()
> 24 return parsed_logs, access_logs, failed_logs
> 25
> ---> 26 parsed_logs, access_logs, failed_logs = parseLogs()
>
> <ipython-input-18-b365aa793252> in parseLogs()
> 2
> 3 def parseLogs():
> ----> 4 parsed_logs=(sc
> 5 .textFile(logFile)
> 6 .map(parseApacheLogLine)
>
> NameError: global name 'sc' is not defined
The problem is that you did never define sc. Therefore python can't find it. (Makes sense, doesn't it?)
Now there are several possible reasons:
- python is case-sensitive. Did you somewhere define SC instead of sc? ... Or Sc instead of sc?
You defined sc in another function (-> you defined it in a function outside parseLogs()). If you only define it there the variable will be local and just be available to the code inside the function. Add the line global sc to the first line of your function to make it accessible everywhere in you whole code.
You simply did not define sc.