'map' object is not subscriptable - python-3.x

I am trying to execute the codes from this link
https://zulko.github.io/blog/2014/06/21/some-more-videogreping-with-python/
import re # module for regular expressions
def convert_time(timestring):
""" Converts a string into seconds """
nums = map(float, re.findall(r'\d+', timestring))
return 3600*nums[0] + 60*nums[1] + nums[2] + nums[3]/1000
with open("Identity_2003.srt") as f:
lines = f.readlines()
times_texts = []
current_times , current_text = None, ""
for line in lines:
times = re.findall("[0-9]*:[0-9]*:[0-9]*,[0-9]*", line)
if times != []:
current_times = map(convert_time, times)
elif line == '\n':
times_texts.append((current_times, current_text))
current_times, current_text = None, ""
elif current_times is not None:
current_text = current_text + line.replace("\n"," ")
print (times_texts)
from collections import Counter
whole_text = " ".join([text for (time, text) in times_texts])
all_words = re.findall("\w+", whole_text)
counter = Counter([w.lower() for w in all_words if len(w)>5])
print (counter.most_common(10))
cuts = [times for (times,text) in times_texts
if (re.findall("please",text) != [])]
from moviepy.editor import VideoFileClip, concatenate
video = VideoFileClip("Identity_2003.mp4")
def assemble_cuts(cuts, outputfile):
""" Concatenate cuts and generate a video file. """
final = concatenate([video.subclip(start, end)
for (start,end) in cuts])
final.to_videofile(outputfile)
assemble_cuts(cuts, "please.mp4")
But the assemble_cuts function is not working . I am using python3.x
it is giving me an error
Traceback (most recent call last):
File "<ipython-input-64-939ee3d73a4a>", line 47, in <module>
assemble_cuts(cuts, "please.mp4")
File "<ipython-input-64-939ee3d73a4a>", line 44, in assemble_cuts
for (start,end) in cuts])
File "<ipython-input-64-939ee3d73a4a>", line 43, in <listcomp>
final = concatenate([video.subclip(start, end)
File "<ipython-input-64-939ee3d73a4a>", line 6, in convert_time
return 3600*nums[0] + 60*nums[1] + nums[2] + nums[3]/1000
TypeError: 'map' object is not subscriptable
Could you help me to solve this problem?

Fixed it.
def convert_time(timestring):
""" Converts a string into seconds """
nums = list(map(float, re.findall(r'\d+', timestring)))
return 3600*nums[0] + 60*nums[1] + nums[2] + nums[3]/1000

Related

TypeError: ord() expected string of length 1, but int found, Traceback (most recent call last):

I am getting an error while encrypting a file.
C:\Users\username>python xor_encryptor.py raw.txt > new.txt
Traceback (most recent call last):
File "C:\Users\username\xor_encryptor.py", line 19, in <module>
ciphertext = xor(plaintext, KEY)
File "C:\Users\username\xor_encryptor.py", line 10, in xor
output_str += chr(ord(current) ^ ord(current_key))
TypeError: ord() expected string of length 1, but int found
The xor_encryptor script is:
import sys
KEY = "x"
def xor(data, key):
key = str(key)
l = len(key)
output_str = ""
for i in range(len(data)):
current = data[i]
current_key = key[i % len(key)]
output_str += chr(ord(current) ^ ord(current_key))
return output_str
def printCiphertext(ciphertext):
print('{ 0x' + ', 0x'.join(hex(ord(x))[2:] for x in ciphertext) + ' };')
try:
plaintext = open(sys.argv[1], "rb").read()
except:
print("File argument needed! %s " % sys.argv[0])
sys.exit()
ciphertext = xor(plaintext, KEY)
print('{ 0x' + ', 0x'.join(hex(ord(x))[2:] for x in ciphertext) + ' };')
Kindly give an appropriate solution.

AttributeError: 'str' object has no attribute 'from_header'

I am new to python. Looks like many people are facing a similar type of error. Solutions to other people's related errors don't solve my error. Why am I getting this error, and how can I fix it?
Thank you.
AttributeError: 'str' object has no attribute 'from_header'
Here's the error report:
*Traceback (most recent call last):
File "./../bin/make_json.py", line 169, in
(headerList, headers) = readHeaders(args.hdr_file)
File "/home3/grad3/kpatel3/new_parser-gen/lib/python/HeaderLib.py", line 445, in readHeaders
from_fields = item.next_header.mapping.from_header.asList()
AttributeError: 'str' object has no attribute 'from_header'
make: *** [../examples/headers-datacenter.json] Error 1
*
Here is my piece of code:
class HeaderInfo:
"""Simple class for returning header info"""
def __init__(self, length, lenIsVar, matchBytes, match):
self.length = length
self.lenIsVar = lenIsVar
self.matchBytes = matchBytes
self.match = match
class HeaderInfoAll:
"""Simple class for returning header info for all length/match combos"""
def __init__(self, lenIsVar, lenBytes, lenMatch, lengths, nxtHdrBytes, nxtHdrMatch, nxtHdrs, defNxtHdrVal):
self.lenIsVar = lenIsVar
self.lenBytes = lenBytes
self.lenMatch = lenMatch
self.lengths = lengths
self.nxtHdrBytes = nxtHdrBytes
self.nxtHdrMatch = nxtHdrMatch
self.nxtHdrs = nxtHdrs
self.defNxtHdrVal = defNxtHdrVal
hdrLengths = {}
def readHeaders(filename):
"""Read all of the headers from a file"""
fh = open(filename)
data = fh.read()
fh.close()
parser = getHeaderBNF()
intRE = re.compile(r'^\d+$')
opRE = re.compile(r'^[+\-*]|<<|>>$')
refCounts = {}
headerList = []
headers = {}
for item in parser.parseString(data, True):
if item.hdr not in headers:
hdr = Header(item.hdr)
headerList.append(hdr)
headers[item.hdr] = hdr
if item.fields != '':
for fieldData in item.fields:
(name, width) = fieldData[0:2]
if width == '*':
width = None
else:
width = int(width)
hdr.addField(name, width)
if len(fieldData) == 3:
hdr.addExtractField(name)
if item.next_header != '':
if item.next_header.field != '':
hdr.setNextHeader(str(item.next_header.field))
else:
from_fields = item.next_header.mapping.from_header.asList()
Can anyone help?

two dimension array square elements using map and pass it for further processing python

Trying to pass a two dimension array of dynamic size as an iter
Square all the values in the array using a map
Process it further to output the code in human readable format.
#array to be converted
arr = [[ 1, 2, 6], [3, 4],[6,8,9,0]]
def lambdaMap(arr):
ans = map(pp3, arr)
return ans
# return the list with all elements squared and pass it to lambdaMap
def pp3(vv):
for i in range(len(str(vv))):
for j in range(len(str(vv[i]))):
vv[i][j] = int( vv[i][j] ) ** 2
return vv
if __name__ == '__main__':
d = []
ans = lambdaMap(arr)
for row in ans:
print(' '.join(map(str, row)))
Error returned
Traceback (most recent call last):
File "stack.py", line 22, in <module>
for row in ans:
File "stack.py", line 11, in pp3
vv[i][j] = int( vv[i][j] ) ** 2
TypeError: 'int' object is not subscriptable***
Here's the working code:
#array to be converted
arr = [[ 1, 2, 6], [3, 4],[6,8,9,0]]
def lambdaMap(arr):
ans = map(pp3, [arr])
return ans
# return the list with all elements squared and pass it to lambdaMap
def pp3(vv):
for i in range(len(vv)):
for j in range(len(vv[i])):
vv[i][j] = int( vv[i][j] ) ** 2
return vv
if __name__ == '__main__':
d = []
ans = lambdaMap(arr)
for row in ans:
print(' '.join(map(str, row)))

Converting a list to integers

here is the problem:
Write a program that computes and prints the average of the numbers in a text file. You should make use of two higher-order functions to simplify the design.
An example of the program input and output is shown below:
Enter the input file name: numbers.txt
The average is 69.83333333333333
here are the numbers in numbers.txt:
45 66 88
100 22 98
and here is my code:
file = input("Enter the input file name: ")
with open(file) as f:
from functools import reduce
def add(x, y): return x + y
data = [45, 66, 88, 100, 22, 98]
total = reduce(add, data)
avg = total / len(data)
print("The average is: ", avg)
if __name__ == "__main__":
main()
the problem is, this works fine when I manually enter items in a list, but when I added the line.strip function and tried to put it in a list, and then convert it using map, this is my code:
file = input("Enter the input file name: ")
with open(file) as f:
for line in f:
line = line.strip()
data = [line]
data = list(map(int, data))
from functools import reduce
def add(x, y): return x + y
total = reduce(add, data)
avg = total / len(data)
print("The average is: ", avg)
if __name__ == "__main__":
main()
I am getting this error:
Traceback (most recent call last):
File "average.py", line 15, in <module>
main()
File "average.py", line 7, in main
data = list(map(int, data))
ValueError: invalid literal for int() with base 10: '100 22 98'
I am terrible at coding, can you please help me understand 1) what the error is 2) is there something wrong with the list not converting the strings to integers?
Thank you!
You have problem with below line of code, this is not spliting the line and adding each item to list. it is adding whole line as an string in list.
data = [line]
e.g.
data = [line]
['11 12 123 123']
data = line.split()
['11', '12', '123', '123']
You need to change your code like below and it should work.
file = input("Enter the input file name: ")
with open(file) as f:
for line in f:
line = line.strip()
data = line.split()
data = list(map(int, data))
from functools import reduce
def add(x, y): return x + y
total = reduce(add, data)
avg = total / len(data)
print("The average is: ", avg)

Python IDLE TypeError: int object not subscriptible

I am making a code that makes a map (not visible), and you can move in it.
I have been working on this code for a week now.
It has a TypeError.
import map
def basicRealm():
player=[0,0]#this is you
Home=[0,0]
Shops=[2,7]
Park=[8,2]
locations = [Home, Shops, Park]
desternation=Park
RealmSize = grid(10)
choice = input("Move north, south, east, or west?[north/south/east/west]")
no = int(input("Number of spaces to move: "))
if choice=='north':
axis=y
elif choice=='south':
axis=y
elif choice=='east':
axis==x
elif choice=='west':
axis=x
else:
pass
nothing=''
if choice=='south' or choice=='east':
no = 0 - no
else:
pass
you_are_here = move(no, player, axis)
basicRealm()
And my map module to run it is :
def atDesternation(location):
global desternation
if desternation==location:
return True
else:
return False
def atLocation(Object,locations):
pos = position(Object)
for i in locations:
if pos==i:
return i
else:
return None
def position(Object):
pos = (Object[0], Object[1])
return pos
def grid(size):
size = ListRange(0, size)
return size
def move(spaces, thing, axis):
here= position(thing)
pos = here[axis] + spaces
return pos
The Output is as follows:
Move north, south, east, or west?[north/south/east/west]north
Number of spaces to move: 1
Traceback (most recent call last):
File "C:\Users\lewis\Desktop\Map1.py", line 35, in <module>
basicRealm()
File "C:\Users\lewis\Desktop\Map1.py", line 29, in basicRealm
print(position(you_are_here))
File "C:\Users\lewis\Desktop\map.py", line 13, in position
pos = (Object[0], Object[1])
TypeError: 'int' object is not subscriptable
>>>
How do I solve this error? Please help.
I am newish to Python and find it very hard to slove Errors.

Resources