How do i extract specific characters from elements in a list in python? - regex

['PRE user_1/\n', '2016-11-30 11:43:32 62944 UserID-12345.jpg\n', '2016-11-28 10:07:24 29227 anpr.jpg\n', '2016-11-30 11:38:30 62944 image.jpg\n']
I have a list of string and i want to extract the 'name\n' part from each element and store it. For example i want to extract 'name\n' from mylist[0], where mylist[0] = 'PRE user_/n'. So user_1/ will be extracted and stored in a variable.
mylist = ['PRE user_1/\n', '2016-11-30 11:43:32 62944 UserID-12345.jpg\n', '2016-11-28 10:07:24 29227 anpr.jpg\n', '2016-11-30 11:38:30 62944 image.jpg\n']
for x in mylist:
i = 0
userid = *extract the 'name\n' from mylist[i]
print userid
i = i+1
How do i do this? Is Regular Expressions the way to do it?, if yes how do i implement it? A code snippet would be very helpful.

Maybe you can do it without regex. You can try my solution:
a = ['PRE user_1/\n', '2016-11-30 11:43:32 62944 UserID-12345.jpg\n', '2016-11-28 10:07:24 29227 anpr.jpg\n', '2016-11-30 11:38:30 62944 image.jpg\n']
def get_name(arg = ""):
b = arg.split(" ")
for i in b:
if "\n" in i:
return i.replace("\n", "")
Output:
print get_name(a[0])
user_1/
print get_name(a[1])
UserID-12345.jpg
print get_name(a[2])
anpr.jpg
print get_name(a[3])
image.jpg
Also in order to fill the example you gave, your code will be:
for x in a:
userid = get_name(x)
print userid
Output:
user_1/
UserID-12345.jpg
anpr.jpg
image.jpg

Related

Combining the values of an array with the values of hash

I have an attributes array which is defined by me and I get an hash both of them which I need to combine into an output array. Please let me know the simplest way to do this.
attributes = [:user_id, :project_id, :task_id, :date, :time_spent, :comment]
entry_hash = {"User"=>1, "Project"=>[8], "Task"=>[87], "Date"=>"05/22/2017", "Time (Hours)"=>"1", "Comment"=>"yes"}
When it is combined I want a hash like
Output = {"user_id"=>1, "project_id"=>8, "task_id"=>87,
"date"=>6/22/2017,"time_spent"=>1,"comment"=>"yes"}
Thanks for the help!
Try this
attributes = [:user_id, :project_id, :task_id, :date, :time_spent, :comment]
# puts attributes.inspect
entry_hash = {"User"=>1, "Project"=>[8], "Task"=>[87], "Date"=>"05/22/2017", "Time (Hours)"=>"1", "Comment"=>"yes"}
# puts entry_hash.inspect
output = {}
a = 0
entry_hash.each do |key,value|
if value.class == Array
output[attributes[a]] = value.first.to_s
#output[attributes[a]] = value.first.to_i //also you can convert them into int
else
output[attributes[a]] = value
end
a += 1
end
#puts output.inspect
#{:user_id=>1, :project_id=>"8", :task_id=>"87", :date=>"05/22/2017", :time_spent=>"1", :comment=>"yes"}

issues when Iterate Map with list as value using groovy

def map = new HashMap<String,List<String>>()
def list = new ArrayList<String>()
def list1 = new ArrayList<String>()
list.add("hello1")
list​.add("world1")
list.add("sample1")
list.add("sample1")​​​​​​​​​​​​​​​​​​​​​​​​
list1.add("hello2")
list1.add("world2")
list1.add("sample2")
list1.add("sample2")
map.put("abc",list)
map.put("bcd",list1)
def data = new ArrayList<String>()
for(e in map){
println "key = ${e.key} value=${e.value}"
// data = "${e.value} as String[]"
data = "${e.value}"
println "size ${data.size()} " --(B)
check(data)
​}
def check(input)
{
println "${input.size()}" ---(A)
for(item in input){
print "$item "​​​​​​​​​​​​​​​​​}
​}​
I have to pass string[] to another java function from this groovy script. so I am trying to read the array list and then convert it into String array. But the problem is when I assign {e.value} to variable data and try to get the size data.size() (both step (A) and (B) ). and the size is 34. It is counting each character not the word as whole from the list. I want to iterate over each word from the list. Kindly let me know how to resolve this problem.
sample output is
key = abc value=[hello1, world1, sample1, sample1]
size 34
Here is the groovified vesion of creating the map and accessing it:
def map = [abc:['hello1', 'world1','sample1', 'sample1'], bcd:['hello2', 'world2','sample2', 'sample2']]
map.collect{ println "key: ${it.key}, list: ${it.value}, and size: ${it.value.size()}" }
Output:
key: abc, list: [hello1, world1, sample1, sample1], and size: 4
key: bcd, list: [hello2, world2, sample2, sample2], and size: 4
If you want to convert a list to an array you can just do it:
def list = ['hello1', 'world1','sample1', 'sample1']
assert list instanceof List
def array = list as String[]
assert array instanceof String[]
assert !(array instanceof List)

Find the Longest and shortest string in a Python List

Hi I am trying to print out the longest & shortest words in a list: Python
The list is = ["Deirdre", "Sandra", "Geraldine", "Keith", "Alyssa"]
i have no idea to where to start, I am new to this and this was on my worksheet this week i have tried a few things but just ant get it.
Thanks
The min function has an optional parameter key that lets you specify a function to determine the "sorting value" of each item.
list_values = ["Deirdre", "Sandra", "Geraldine", "Keith", "Alyssa"]
print min(list_values, key=len) # prints "Keith"
print max(list_values, key=len) # prints "Geraldine"
You can use python's built-in min and max functions:
l = ["Deirdre", "Sandra", "Geraldine", "Keith", "Alyssa"]
shortest_name = min(l, key=len)
longest_name = max(l, key=len)
print(shortest_name, longest_name)
You can use the key parameter of the function min or max like the following :
myList = ["Deirdre", "Sandra", "Geraldine", "Keith", "Alyssa"]
minName = min(l, key=len)
maxName = max(l, key=len)
print "shortest name: "
print(minName)
print "longest name: "
print(maxName)

How can I convert a list into the following format?

I have a task to find prime factors. In which I want my output in format like 50="2*5*5".
I have my output in list form
FactorList=[2,5,5]
How can I convert it into 50="2*5*5"
If you simply want to print FactorList in that format here is some simple code to do that:
FactorList=[2,5,5]
print "50=" + str(FactorList[0]) + "*" + str(FactorList[1]) + "*" + str(FactorList[2])
This converts each element of FactorList into a string and inserts it into your printed output.
If you want something more general that allows you to input any length list of this kind you might try this:
def printInFormat (list):
value = list[0]
length = len(list)
for index in range(1, length):
value = value * list[index]
string = str(value) + "="
for index in range(length-1):
string = string + str(list[index]) + "*"
string = string + str(list[length-1])
return string
FactorList=[2,5,5]
print printInFormat(FactorList)
This code follows the same idea, but uses a function to generalize it. I find the length of the list and use a for loop to find the overall value (50) and another for loop to cycle through all of the elements and print them out.
Assume s is the list, you can using code like below:
s = [2, 5, 5]
print '*'.join(['%s'] * len(s)) % tuple(s)

Multiple inputs to produce wanted output

I am trying to create a code that takes the user input, compares it to a list of tuples (shares.py) and then prints the values in a the list. for example if user input was aia, this code would return:
Please list portfolio: aia
Code Name Price
AIA Auckair 1.50
this works fine for one input, but what I want to do is make it work for multiple inputs.
For example if user input was aia, air, amp - this input would return:
Please list portfolio: aia, air, amp
Code Name Price
AIA Auckair 1.50
AIR AirNZ 5.60
AMP Amp 3.22
This is what I have so far. Any help would be appreciated!
import shares
a=input("Please input")
s1 = a.replace(' ' , "")
print ('Please list portfolio: ' + a)
print (" ")
n=["Code", "Name", "Price"]
print ('{0: <6}'.format(n[0]) + '{0:<20}'.format(n[1]) + '{0:>8}'.format(n[2]))
z = shares.EXCHANGE_DATA[0:][0]
b=s1.upper()
c=b.split()
f=shares.EXCHANGE_DATA
def find(f, a):
return [s for s in f if a.upper() in s]
x= (find(f, str(a)))
print ('{0: <6}'.format(x[0][0]) + '{0:<20}'.format(x[0][1]) + ("{0:>8.2f}".format(x[0][2])))
shares.py contains this
EXCHANGE_DATA = [('AIA', 'Auckair', 1.5),
('AIR', 'Airnz', 5.60),
('AMP', 'Amp',3.22),
('ANZ', 'Anzbankgrp', 26.25),
('ARG', 'Argosy', 12.22),
('CEN', 'Contact', 11.22)]
I am assuming a to contain values in the following format 'aia air amp'
raw = a # just in case you want the original string at a later point
toDisplay = []
a = a.split() # a now looks like ['aia','air','amp']
for i in a:
temp = find(f, i)
if(temp):
toDisplay.append(temp)
for i in toDisplay:
print ('{0: <6}'.format(i[0][0]) + '{0:<20}'.format(i[0][1]) + ("{0:>8.2f}".format(i[0][2])))
Essentially what I'm trying to do is
Split the input into a list
Do exactly what you were doing for a single input for each item in that list
Hope this helps!