I have a string as given below
dit ='{p_d: {a:3, what:3.6864e-05, s:lion, sst:{c:-20, b:6, p:panther}}}'
And I have a list of elements which I wanted to search in the above string and replace them with double quotes.
['', 'p_d', '', '', 'a', '3', '', 'what', '3.6864e-05', '', 's', 'lion', '', 'sst', '', 'c', '-20', '', 'b', '6', '', 'p', 'panther', '', '', '']
If I do search and replace using simple .replace it doesn't work as expected and can understand
import yaml
import ast
import json
import re
rep = {":": " ", "'":" ", "{":" ", "}":" ", ",": " "}
quot = "\""
dit = '{p_d: {a:3, what:3.6864e-05, s:lion, sst:{c:-20, b:6, p:panther}}}'
def replace_all(text, dic):
for i, j in dic.items():
text = text.replace(i, j)
print("replace_all: text {}".format(text))
return text
element_list_temp = replace_all(dit, rep)
element_list = element_list_temp.split(" ")
for z in element_list:
if z != "" and z in dit:
dit = dit.replace(z, quot+z+quot)
print(dit)
Output:
{""p"_d": {"a":"3", wh"a"t:"3"."6"8"6"4e-05, "s":"lion", "s""s"t:{"c":"-20", "b":"6", "p":"p""a"nther}}}
Desired Output:
'{"p_d": {"a":"3", "what":"3.6864e-05", "s":"lion", "sst":{"c":"-20", "b":"6", "p":"panther"}}}'
How to exactly match the string in the list one by one and replace them with double quotes.
Updates:
Different input
import yaml
import ast
import json
import re
rep = {":": " ", "'":" ", "{":" ", "}":" ", ",": " "}
quot = "\""
# dit = '{p_d: {a:3, what:3.6864e-05, s:lion, sst:{c:-20, b:6, p:panther}}}'
dit = "'{p_d: '{a:3, what:3.6864e-05, s:lion, vec_mode:'{2.5, -2.9, 3.4, 5.6, -8.9, -5.67, 2, 2, 2, 2, 5.4, 2, 2, 6.545, 2, 2}, sst:'{c:-20, b:6, p:panther}}}"
seps = ":'{}, "
val_strings = re.findall(f"[^{seps}]+", dit)
print("val_strings: {}".format(val_strings))
sep_strings = re.findall(f"[{seps}]+", dit)
print("sep_strings: {}".format(sep_strings))
seq = [f'{b}"{v}"' for b, v in zip(sep_strings, val_strings)] + sep_strings[-1:]
print("sep: {}".format(seq))
dit = "".join(seq)
print(dit)
Dict = json.loads(dit)
print(Dict)
result = yaml.dump(Dict)
print(result)
print(result.replace("'",""))
Output from above code
Think its failing because of the key:value pair of the dictionary. Checking at my end as well if there is a way to print them as arrays.
val_strings: ['p_d', 'a', '3', 'what', '3.6864e-05', 's', 'lion', 'vec_mode', '2.5', '-2.9', '3.4', '5.6', '-8.9', '-5.67', '2', '2', '2', '2', '5.4', '2', '2', '6.545', '2', '2', 'sst', 'c', '-20', 'b', '6', 'p', 'panther']
sep_strings: ["'{", ": '{", ':', ', ', ':', ', ', ':', ', ', ":'{", ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', '}, ', ":'{", ':', ', ', ':', ', ', ':', '}}}']
sep: ['\'{"p_d"', ': \'{"a"', ':"3"', ', "what"', ':"3.6864e-05"', ', "s"', ':"lion"', ', "vec_mode"', ':\'{"2.5"', ', "-2.9"', ', "3.4"', ', "5.6"', ', "-8.9"', ', "-5.67"', ', "2"', ', "2"', ', "2"', ', "2"', ', "5.4"', ', "2"', ', "2"', ', "6.545"', ', "2"', ', "2"', '}, "sst"', ':\'{"c"', ':"-20"', ', "b"', ':"6"', ', "p"', ':"panther"', '}}}']
'{"p_d": '{"a":"3", "what":"3.6864e-05", "s":"lion", "vec_mode":'{"2.5", "-2.9", "3.4", "5.6", "-8.9", "-5.67", "2", "2", "2", "2", "5.4", "2", "2", "6.545", "2", "2"}, "sst":'{"c":"-20", "b":"6", "p":"panther"}}}
Traceback (most recent call last):
File "./ditoyaml_new.py", line 36, in <module>
Dict = json.loads(dit)
File "/usr/lib64/python3.6/json/__init__.py", line 354, in loads
return _default_decoder.decode(s)
File "/usr/lib64/python3.6/json/decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib64/python3.6/json/decoder.py", line 357, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Expected Output with the json.load and dump as dictionary and if the key: value dictionary pair isnt available and put something like list or array. Checking at my end as well.
p_d:
a: 3
s: lion
sst:
b: 6
c: -20
p: panther
vec_mode:
[-8.9,
-5.67,
-2.9,
2,
2.5,
3.4,
5.4,
5.6,
6.545]
what: 3.6864e-05
Here is one way using regular expressions
import re
dit = '{p_d: {a:3, what:3.6864e-05, s:lion, sst:{c:-20, b:6, p:panther}}}'
seps = ":'{}, "
val_strings = re.findall(fr"[^{seps}]+", dit)
sep_strings = re.findall(fr"[{seps}]+", dit)
seq = [f'{b}"{v}"' for b, v in zip(sep_strings, val_strings)] + sep_strings[-1:]
dit = "".join(seq)
print(dit)
Output:
{"p_d": {"a":"3", "what":"3.6864e-05", "s":"lion", "sst":{"c":"-20", "b":"6", "p":"panther"}}}
JSON test:
import json
print(json.loads(dit))
Output:
{'p_d': {'a': '3', 'what': '3.6864e-05', 's': 'lion', 'sst': {'c': '-20', 'b': '6', 'p': 'panther'}}}
I am working with a pandas dataframe (the dataframe is called market_info_df):
And I have the following Python code:
market_info_df['is_and_mp'] = market_info_df['issue_status'] + market_info_df['market_phase']
no_collision_issue_status = ['000', '200', '203', '204', '300']
MARKET_STATES_DICT = {
('000', ' '): MARKET_STATES.CLOSED,
('100', ' ', 'F'): MARKET_STATES.OPENING_AUCTION,
('200', ' '): MARKET_STATES.CONTINUOUS_TRADING,
('203', ' '): MARKET_STATES.UNSCHEDULED_AUCTION,
('204', ' '): MARKET_STATES.UNSCHEDULED_AUCTION,
('100', 'B0'): MARKET_STATES.UNSCHEDULED_AUCTION,
('200', 'B1'): MARKET_STATES.CONTINUOUS_TRADING,
('400', 'C0'): MARKET_STATES.HALTED,
('400', 'C1'): MARKET_STATES.CONTINUOUS_TRADING,
('400', 'D0'): MARKET_STATES.HALTED,
('400', 'D1'): MARKET_STATES.POST_TRADE}
I am trying to write a condition such that if the is_and_mp is in the no_collision_issue_status list, OR the trading_status is not , then use the MARKET_STATES_DICT to map a new column called market_state.
Here is what I have written, but I get an error TypeError: unhashable type: 'Series':
market_info_df.loc[(market_info_df['is_and_mp'] in no_collision_issue_status) | (~market_info_df['trading_state'] == ' '),
'market_state'] = MARKET_STATES_DICT[(market_info_df['issue_status'], market_info_df['trading_state'])]
I understand what is wrong and why I am getting the error, but I am not sure how to fix it!
Use apply function on dataframe. Check for the desired condition as you have written. If true then return the value from dict else return None:
market_info_df["market_state"] = market_info_df.apply(lambda row: MARKET_STATES_DICT[(row["is_and_mp"],row["trading_status"])] if row["is_and_mp"] in no_collision_issue_status or row["trading_status"] != " " else None, axis=1)
Full example with dummy data:
market_info_df = pd.DataFrame(data=[["10","0","B0"],["20","0"," "],["40","0","D1"]], columns=["issue_status", "market_phase", "trading_status"])
market_info_df['is_and_mp'] = market_info_df['issue_status'] + market_info_df['market_phase']
no_collision_issue_status = ['000', '200', '203', '204', '300']
MARKET_STATES_DICT = {
('000', ' '): "CLOSED",
('100', ' ', 'F'): "OPENING_AUCTION",
('200', ' '): "CONTINUOUS_TRADING",
('203', ' '): "UNSCHEDULED_AUCTION",
('204', ' '): "UNSCHEDULED_AUCTION",
('100', 'B0'): "UNSCHEDULED_AUCTION",
('200', 'B1'): "CONTINUOUS_TRADING",
('400', 'C0'): "HALTED",
('400', 'C1'): "CONTINUOUS_TRADING",
('400', 'D0'): "HALTED",
('400', 'D1'): "POST_TRADE"}
market_info_df["market_state"] = market_info_df.apply(lambda row: MARKET_STATES_DICT[(row["is_and_mp"],row["trading_status"])] if row["is_and_mp"] in no_collision_issue_status or row["trading_status"] != " " else None, axis=1)
[Out]:
issue_status market_phase trading_status is_and_mp market_state
0 10 0 B0 100 UNSCHEDULED_AUCTION
1 20 0 200 CONTINUOUS_TRADING
2 40 0 D1 400 POST_TRADE
I have to sort these words in to a sentence.
This is my list, with the numbers:
sms=['Szentírás ', 'bölcs ', 'a ', 'már ', 'szükséges ', 'mondhat ', 'biztosak ', 'a ',
'feladata, ', 'Mivel ', 'ellent ', 'a ', 'érzéki ', 'azokkal ', 'következtetésekkel, ',
'a ', 'vagyunk ', 'a ', 'tapasztalataink ', 'szöveg ', 'azon ', 'igazság ', 'sose ',
'ami ', 'hogy ', 'melyekben ', 'kísérletek ', 'megtalálják ', 'által.', 'két ', 'fizikai ',
'egymásnak, ', 'egyezik ', 'és ', 'értelmezőinek ', 'értelmezését, ']
sorrend=[8,9,15,26,33,4,27,11,12,0,5,32,29,21,24,22,28,7,30,16,17,2,3,19,13,25,34,14,35,1,23,6,20,31,10,18]
and I have to get this sentence:
Mivel két igazság sose mondhat ellent egymásnak, a Szentírás bölcs értelmezőinek a feladata, hogy megtalálják a szöveg azon értelmezését, ami egyezik azokkal a fizikai következtetésekkel, melyekben már biztosak vagyunk érzéki tapasztalataink és a szükséges kísérletek által.
How can I sort it like that?
Thanks.
You could try something like this:
dict(sorted(zip(sorrend,sms))).values()
For your shortened example:
>>> sms=['love', 'I', 'much', 'so', 'you']
>>> sorrend=[2,1,5,4,3]
>>> ' '.join(dict(sorted(zip(sorrend,sms))).values())
'I love you so much'
Finally I've solved this riddle:
words = {}
for i in range(len(sorrend)):
words[sorrend[i]] = sms[i]
for i in range(len(sorrend)):
print(words[i], end=' ')
Output:
Mivel két igazság sose mondhat ellent egymásnak, a Szentírás bölcs értelmezőinek a feladata, hogy megtalálják a szöveg azon értelmezését, ami egyezik azokkal a fizikai következtetésekkel, melyekben már biztosak vagyunk érzéki tapasztalataink és a szükséges kísérletek által.
puzzle = [[' 1', ' 2', ' 3', ' 4'], [' 5', ' 6', ' 7', ' 8'],[ ' 9', '10', '11', '12'], ['13', '14', '15', ' X']]
def find_pos(alist, item):
for i in alist:
for j in range(4):
if i[j] == item:
row = alist.index(i)
col = j
find_pos(puzzle,' X')
a = row
print(a)
I think I defined the name row by running the function find_pos, if not, how to fix it to get row
Do not put any print in the find_pos function
Just return the values from the function:
puzzle = [[' 1', ' 2', ' 3', ' 4'], [' 5', ' 6', ' 7', ' 8'],[ ' 9', '10', '11', '12'], ['13', '14', '15', ' X']]
def find_pos(alist, item):
for i in alist:
for j in range(4):
if i[j] == item:
row = alist.index(i)
col = j
return row, col
row, col = find_pos(puzzle,' X')
print(row)
Note that if the item isn't found, it will return None (because every function that doesn't return anything returns None by default), in which case the code will throw an error.