For some reason x.split(':', 1)[-1] doesn't do anything. Could someone explain and maybe help me?
I'm trying to remove the data before : (including ":") but it keeps that data anyway
Code
data = { 'state': 1, 'endTime': 1518852709307, 'fileSize': 000000 }
data = data.strip('{}')
data = data.split(',')
for x in data:
x.split(':', 1)[-1]
print(x)`
Output
"state":1
"endTime":1518852709307
"fileSize":16777216
It's a dictonary, not a list of strings.
I think this is what you're looking for:
data = str({"state":1,"endTime":1518852709307,"fileSize":000000}) #add a str() here
data = data.strip('{}')
data = data.split(',')
for x in data:
x=x.split(':')[-1] # set x to x.split(...)
print(x)
The script below prints out:
1
1518852709307
0
Here is a one-liner version:
print (list(map(lambda x:x[1],data.items())))
Prints out:
[1, 1518852709307, 0]
Which is a list of integers.
Seems like you just want the values in the dictionary
data = {"state":1,"endTime":1518852709307,"fileSize":000000}
for x in data:
print(data[x])
I'm not sure, but I think it's because the computer treats "state" and 1 as separate objects. Therefore, it is merely stripping the string "state" of its colons, of which there are none.
You could make the entire dictionary into a string by putting:
data = str({ Your Dictionary Here })
then, print what you have left in for "for x in data" statement like so:
for x in data:
b = x.split(':', 1)[-1] # creating a new string
print(b)
data in your code is a dictionary. So you can just access your the values of it like data[state] which evaluates to 1.
If you get this data as a string like:
data = "{'state':1, 'endTime':1518852709307, 'fileSize':000000}"
You could use json.loads to convert it into a dictionary and access the data like explained above.
import json
data = '{"state":1, "endTime":1518852709307, "fileSize":0}'
data = json.loads(data)
for _,v in data.items():
print(v)
If you want to parse the string yourself this should work:
data = '{"state":1,"endTime":1518852709307,"fileSize":000000}'
data = data.strip('{}')
data = data.split(',')
for x in data:
x=x.split(':')[-1]
print(x)
Related
I have a string output and I would like to extract the str_data out. That is the value in str_data. Currently I'm using the below code but I think it can be improved on. The below code does not work well with str_data=[''] and str_data=['L'm'] as it return list/index out of range error. str_data contains language information, so it could be empty or contain words like it's. Anyway to improve this? Thanks
right = result.split("str_data=['")[1]
final = right.split("'], extra='")[0]
Example 1:
result = TensorSet(tensors={'result': Tensor(shape=['5'], str_data=['ขอคุยด้วยหน่อย'], extra={})}, extra={}
Example 2:
result = TensorSet(tensors={'result': Tensor(shape=['102'], str_data=[''], extra={})}, extra={}
Example 3:
result = TensorSet(tensors={'result': Tensor(shape=[], str_data=['L'm'], extra={})}, extra={}
I would like to extract out:
example_1_result = 'ขอคุยด้วยหน่อย'
example_2_result = ''
example_3_result = 'L'm'
Assuming TensorFlow(...) is a string, that will always be formatted with the same arguments, then something like this will work:
final = result.split(",")[1].split("str_data=")[1].replace("[","").replace("]","")
Here's a breakdown:
Example input:
result = "TensorSet(tensors={'result': Tensor(shape=['5'], str_data=['ขอคุยด้วยหน่อย'], extra={})}, extra={})"
>>> result.split(",")[1]
" str_data=['ขอคุยด้วยหน่อย']"
>>> data = result.split(",")[1]
>>> data.split("str_data=")[1]
"['ขอคุยด้วยหน่อย']"
>>> content = data.split("str_data=")[1]
>>> content.replace("[","").replace("]","")
"'ขอคุยด้วยหน่อย'"
>>> final = content.replace("[","").replace("]","")
>>> final
"'ขอคุยด้วยหน่อย'"
I have an array formatted like this:
[-22.99253267 -83.23210952 77.71126322 43.99377722 -41.75731176 89.02862477]
I would like to print this array to receive this result
[-22.992 -83.232 77.711 43.993 -41.757 89.028]
I know It will be a similar result if I use np.set_printoptions(precision=3), but I would like to know how to receive this result using 9.3f.
To print the data in column :
for data in x:
print '{:9.3f}'.format(data)
or
To print the data in row :
(don't forget import sys)
for data in x:
sys.stdout.write('{:9.3f}'.format(data))
Using String.format()
list = [-22.99253267, -83.23210952, 77.71126322, 43.99377722, -41.75731176, 89.02862477]
for numbers in list :
print('{:9.3f}'.format(data))
I receive the output
-22.993
-83.232
77.711
43.994
-41.757
89.029
EDIT
Following OP's comment, here's an update which would append all elements into a list.
y = []
list = [-22.99253267, -83.23210952, 77.71126322, 43.99377722, -41.75731176, 89.02862477]
for numbers in list:
x = '{:9.3f}'.format(data)
y.append(x)
print(y)
Output
[' -22.993', ' -83.232', ' 77.711', ' 43.994', ' -41.757', ' 89.029']
I am new to this whole python and the data mining.
Let's say I have a list of string called data
data[0] = ['I want to make everything lowercase']
data[1] = ['How Do I Do It']
data[2] = ['With A Large DataSet']
and so on. My len(data) gives 50000.
I have tried
{k.lower(): v for k, v in data.items()}
and it gives me error saying that 'list' object has no attribute 'items'.
and I have also tried using .lower() and it is giving me the same AtrributeError.
How do I recursively call the lower() function in all the data[:50000] to make all the of strings in the data to all lowercase?
EDIT:
For more details: I have a json file with datas such as:
{'review/a': 1.0, 'review/b':2.0, 'review/c':This IS the PART where I want to make all loWerCASE}
Then I call a function to get the specific reviews that I want to make all lower case to
def lowerCase(datum):
feat = [datum['review/c']]
return feat
lowercase = [lowercase(d) for d in data]
Now that I have all the 'review/c' information in my lowercase list.
I want to make all of that strings to lower case
if your list data like this:
data = ['I want to make everything lowercase', '', '']
data = [k.lower() for k in data]
if your list data is a list of string list:
data = [['I want to make everything lowercase'], ['']]
data = [[k.lower()] for l in data for k in l]
the fact is that list don't has attribute 'items'
You need a list comprehension, not a dict comprehension:
lowercase_data = [v.lower() for v in data]
Id like to know what it takes to remove a comma from the last line within a for loop in python. When I run the script it gives me the below output(after code section). I want to remove the comma at the end of fourth line "{"{#MACRO}":"queue4"}," Please can someone help?
By the way if there is a better way to construct the block please share the ideas. I'm a beginner and like to learn. :)
Code:
import json
import urllib
import string
Url= "http://guest:guest#localhost:55672/api/queues"
Response = urllib.urlopen(Url)
Data = Response.read()
def Qlist(Name):
Text = ''' {{"{{#MACRO}}":"{Name}"}},'''.format(Name=Name)
print Text
X_json = json.loads(Data)
print '''{
"data":['''
for i in X_json:
VV = i['name']
Qlist(VV)
print ''']
}'''
Below is the Output:
{
"data":[
{"{#MACRO}":"queue1"},
{"{#MACRO}":"queue2"},
{"{#MACRO}":"queue3"},
{"{#MACRO}":"queue4"},
]
}
Thanks so much
You can modify your loop as follows.
# Create and initialize a dictionary (Associative Array)
# data['data'] is an empty list.
# Variable name (data in this case) can be anything you want.
# 'data' is a key. notice the quotations around. it's not a variable.
# I used 'data' as the key, becasue you wanted your final output to include that part.
data = {"data": []}
for i in X_json:
# We are not calling the data dictionary here.
# We are accessing the empty list we have created inside the `data` dict (above) using data['data'] syntax.
# We can use the append function to add an item to a list.
# We create a new dictionary for every `name` item found in your json array and
# append that new dictionary to the data['data'] list.
data['data'].append({"{#MACRO}": i['name']})
print(json.dumps(data))
# or print json.dumps(data, indent=True)
Read more about json.dumps() here. You can read more about python's list and dictionary here
Don't print inside Qlist - instead return a value; then you can join all returned values using comma as separator:
def Qlist(Name):
Text = ''' {{"{{#MACRO}}":"{Name}"}}'''.format(Name=Name)
return Text
print '''{
"data":[''' +
',\n'.join([ Qlist(i['name']) for i in X_json ]) +
''']
}'''
And anyway, using json.dumps is likely a better idea.
I have a string that contains dictionary:
data = 'IN.Tags.Share.handleCount({"count":17737,"fCnt":"17K","fCntPlusOne":"17K","url":"www.test.com\\/"});'
How can i get value of an dictionary element count? (In my case 17737)
P.S. maybe I need to delete IN.Tags.Share.handleCount from string before getting a dictionary by i.e.
k = data.replace("IN.Tags.Share.handleCount", "") but the problem that '()' remains after delete?
Thanks
import re, ast
data = 'IN.Tags.Share.handleCount({"count":17737,"fCnt":"17K","fCntPlusOne":"17K","url":"www.test.com\/"});'
m = re.match('.*({.*})', data)
d = ast.literal_eval(m.group(1))
print d['count']