I am doing a project in university and I'm working on molecular mass calculator.
This is the code I made.
element_mass = {'H': 1.00794, 'He': 4.002602, 'Li': 6.941, 'Be': 9.012182, 'B': 10.811, 'C': 12.0107, 'N': 14.0067,
'O': 15.9994, 'F': 18.9984032, 'Ne': 20.1797, 'Na': 22.98976928, 'Mg': 24.305, 'Al': 26.9815386,
'Si': 28.0855, 'P': 30.973762, 'S': 32.065, 'Cl': 35.453, 'Ar': 39.948, 'K': 39.0983, 'Ca': 40.078,
'Sc': 44.955912, 'Ti': 47.867, 'V': 50.9415, 'Cr': 51.9961, 'Mn': 54.938045,
'Fe': 55.845, 'Co': 58.933195, 'Ni': 58.6934, 'Cu': 63.546, 'Zn': 65.409, 'Ga': 69.723, 'Ge': 72.64,
'As': 74.9216, 'Se': 78.96, 'Br': 79.904, 'Kr': 83.798, 'Rb': 85.4678, 'Sr': 87.62, 'Y': 88.90585,
'Zr': 91.224, 'Nb': 92.90638, 'Mo': 95.94, 'Tc': 98.9063, 'Ru': 101.07, 'Rh': 102.9055, 'Pd': 106.42,
'Ag': 107.8682, 'Cd': 112.411, 'In': 114.818, 'Sn': 118.71, 'Sb': 121.760, 'Te': 127.6,
'I': 126.90447, 'Xe': 131.293, 'Cs': 132.9054519, 'Ba': 137.327, 'La': 138.90547, 'Ce': 140.116,
'Pr': 140.90465, 'Nd': 144.242, 'Pm': 146.9151, 'Sm': 150.36, 'Eu': 151.964, 'Gd': 157.25,
'Tb': 158.92535, 'Dy': 162.5, 'Ho': 164.93032, 'Er': 167.259, 'Tm': 168.93421, 'Yb': 173.04,
'Lu': 174.967, 'Hf': 178.49, 'Ta': 180.9479, 'W': 183.84, 'Re': 186.207, 'Os': 190.23, 'Ir': 192.217,
'Pt': 195.084, 'Au': 196.966569, 'Hg': 200.59, 'Tl': 204.3833, 'Pb': 207.2, 'Bi': 208.9804,
'Po': 208.9824, 'At': 209.9871, 'Rn': 222.0176, 'Fr': 223.0197, 'Ra': 226.0254, 'Ac': 227.0278,
'Th': 232.03806, 'Pa': 231.03588, 'U': 238.02891, 'Np': 237.0482, 'Pu': 244.0642, 'Am': 243.0614,
'Cm': 247.0703, 'Bk': 247.0703, 'Cf': 251.0796, 'Es': 252.0829, 'Fm': 257.0951, 'Md': 258.0951,
'No': 259.1009, 'Lr': 262, 'Rf': 267, 'Db': 268, 'Sg': 271, 'Bh': 270, 'Hs': 269, 'Mt': 278,
'Ds': 281, 'Rg': 281, 'Cn': 285, 'Nh': 284, 'Fl': 289, 'Mc': 289, 'Lv': 292, 'Ts': 294, 'Og': 294,
'ZERO': 0}
import re
formula=input("화학식을 입력해주세요:")
s=re.findall('([A-Z][a-z]?)([0-9]*)',formula)
for element,count in s:
if count==' ':
count==1
totalmass=sum(int(count)*element_mass[element])
print('화학식량은',' ',total_mass,'입니다.')
'화학식을 입력해주세요' means 'Input chemical formula', and '화학식량은 total_mass입니다' means 'Molecular mass is total_mass'.
When I run the code, it keeps printing
Traceback (most recent call last):
File "C:\Users\Lenovo\Desktop\코딩기말\연습.py", line 28, in <module>
totalmass=sum(int(count)*element_mass[element])
ValueError: invalid literal for int() with base 10: ''
I don't know how to solve this problem.
Did you notice the '' in the error message:
ValueError: invalid literal for int() with base 10: ''
>>> int('')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: ''
So it basically means that you trying to convert an empty string to int.
Related
I have a variable which stores below dictionary
initial_ltp =
{'s': 'ok',
'd': [{'n': 'MCX:CRUDEOIL23JANFUT',
's': 'ok',
'v': {'ch': 47.0,
'chp': 0.74,
'lp': 6377.0,
'spread': 2.0,
'ask': 6379.0,
'bid': 6377.0,
'open_price': 6330.0,
'high_price': 6393.0,
'low_price': 6305.0,
'prev_close_price': 6330.0,
'volume': 8410,
'short_name': 'CRUDEOIL23JANFUT',
'exchange': 'MCX',
'description': 'MCX:CRUDEOIL23JANFUT',
'original_name': 'MCX:CRUDEOIL23JANFUT',
'symbol': 'MCX:CRUDEOIL23JANFUT',
'fyToken': '1120230119244999',
'tt': 1673481600,
'cmd': {'t': 1673518200,
'o': 6376.0,
'h': 6378.0,
'l': 6375.0,
'c': 6377.0,
'v': 19,
'tf': '15:40'}}},
{'n': 'MCX:SILVERMIC23FEBFUT',
's': 'ok',
'v': {'ch': 485.0,
'chp': 0.71,
'lp': 68543.0,
'spread': 5.0,
'ask': 68545.0,
'bid': 68540.0,
'open_price': 68200.0,
'high_price': 68689.0,
'low_price': 68200.0,
'prev_close_price': 68058.0,
'volume': 49595,
'short_name': 'SILVERMIC23FEBFUT',
'exchange': 'MCX',
'description': 'MCX:SILVERMIC23FEBFUT',
'original_name': 'MCX:SILVERMIC23FEBFUT',
'symbol': 'MCX:SILVERMIC23FEBFUT',
'fyToken': '1120230228242738',
'tt': 1673481600,
'cmd': {'t': 1673518200,
'o': 68525.0,
'h': 68543.0,
'l': 68524.0,
'c': 68543.0,
'v': 140,
'tf': '15:40'}}}]}
I am trying to collect ('n') and ('lp') and save it in a different dictionary using code:
if 'd' in initial_ltp.keys():
ltp[initial_ltp['d'][0]['n']] = initial_ltp['d'][0]['v']['lp']
But it is only taking the first n and lp
ltp
{'MCX:CRUDEOIL23JANFUT': 6377.0}
My expected output:
ltp
{'MCX:CRUDEOIL23JANFUT': 6377.0, 'MCX:SILVERMIC23FEBFUT': 68543.0}
How can I get both the values
You have to loop over the list. Using ltp[initial_ltp['d'][0] will just extract for the first element of the list.
Here is an example:
results = {}
for doc in initial_ltp["d"]:
results[doc["n"]] = doc["v"]["lp"]
print(results)
Use the following approach with dict comprehension:
ltp = {d['n']:d['v']['lp'] for d in initial_ltp['d']} if 'd' in initial_ltp else {}
{'MCX:CRUDEOIL23JANFUT': 6377.0, 'MCX:SILVERMIC23FEBFUT': 68543.0}
when you use the "=" operator, it replaces your value in the dictionary key.
you want to add keys to your dictionary so I suggest using this:
if 'd' in initial_ltp.keys():
for o in initial_ltp['d']:
if n in o:
ltp[initial_ltp['d'][0]['n']].append(initial_ltp['d'][0]['v']
['lp']
It's because you selected only first item in the 'd'.
try a loop like this:
ltp={}
if 'd' in initial_ltp.keys():
for i in range(len(initial_ltp['d'])):
ltp[initial_ltp['d'][i]['n']] = initial_ltp['d'][i]['v']['lp']
print (ltp)
Output:
{'MCX:CRUDEOIL23JANFUT': 6377.0, 'MCX:SILVERMIC23FEBFUT': 68543.0}
Am getting API response Like Below
https://imgur.com/a/uVcLfF4
{'s': 'ok', 'd':
[
{'n': 'NSE:SBIN22JUL485CE', 's': 'ok', 'v': {'ch': -2.25, 'chp': -17.05, 'lp': 10.95, 'spread': 0.25, 'ask': 10.95, 'bid': 10.7, 'open_price': 11.5, 'high_price': 15.05, 'low_price': 10.45, 'prev_close_price': 13.2, 'volume': 1161000, 'short_name': 'SBIN22JUL485CE', 'exchange': 'NSE', 'description': 'NSE:SBIN22JUL485CE', 'original_name': 'NSE:SBIN22JUL485CE', 'symbol': 'NSE:SBIN22JUL485CE', 'fyToken': '1011220728149794', 'tt': 1657584000, 'cmd': {'t': 1657620000, 'o': 10.95, 'h': 10.95, 'l': 10.95, 'c': 10.95, 'v': 1500, 'tf': '15:30'}}
},
{'n': 'NSE:SBIN22JUL480CE', 's': 'ok', 'v': {'ch': -2.65, 'chp': -16.46, 'lp': 13.45, 'spread': 0.1, 'ask':
13.45, 'bid': 13.35, 'open_price': 15.3, 'high_price': 18.45, 'low_price': 12.9, 'prev_close_price': 16.1, 'volume': 4270500, 'short_name': 'SBIN22JUL480CE', 'exchange': 'NSE', 'description': 'NSE:SBIN22JUL480CE', 'original_name': 'NSE:SBIN22JUL480CE', 'symbol': 'NSE:SBIN22JUL480CE', 'fyToken': '1011220728128799', 'tt': 1657584000, 'cmd': {'t': 1657619940, 'o': 13.45, 'h': 13.45, 'l': 13.45, 'c': 13.45, 'v': 28500, 'tf': '15:29'}}
}
]
}
How to read and print this in python like below.
Name= NSE:SBIN22JUL485CE
ch = -2.25
chp = -17.05
volume = 1161000
Name= NSE:SBIN22JUL480CE
ch = -2.65
chp = -16.46
volume = 4270500
It looks like json, if you have that text in a variable, you can use the python json librarie for decoding it, and get a dictionary.
import json
text = '...' # The variable that contains the response
data = json.loads(text)
for entry in data['d']:
print(f'Name = {entry["n"]}')
print(f'ch = {entry["v"]["ch"]}')
print(f'chp = {entry["v"]["chp"]}')
print(f'volume = {entry["v"]["volume"]}')
print('')
If for some reason, in the text, the quotes are single quotes ' insted of double ", you should need to replace it, before the json parsing:
text = text.replace("'", '"')
If it is already a dict, just print the content:
mydict = <API response>
if 's' in mydict and mydict['s'] == 'ok':
for data in mydict['d']:
print('Name:', data['n'])
print('ch:', data['v']['ch'])
print('chp:', data['v']['chp'])
print('volume:', data['v']['volume'])
print()
If it is not a dict then you need to convert the content before:
import json
content = <API response>
mydict = json.loads(content)
<code to print above>
The problem I have here is googletrans API suddenly stopped working, just like this:
result = translator.translate('祝您新年快乐', src='zh-cn', dest='en')
result.text
Output:
'祝您新年快乐'
It should return English but just printed the original text. Then I checked what goes wrong. I found that googletrans detect all languages as english, like this:
print(translator.detect('이 문장은 한글로 쓰여졌습니다.'))
print(translator.detect('祝您新年快乐'))
Output:
Detected(lang=en, confidence=1)
Detected(lang=en, confidence=1)
Finally I checked if those languages are available in the library. It is.
print(googletrans.LANGUAGES)
output:
{'af': 'afrikaans', 'sq': 'albanian', 'am': 'amharic', 'ar': 'arabic', 'hy': 'armenian', 'az': 'azerbaijani', 'eu': 'basque', 'be': 'belarusian', 'bn': 'bengali', 'bs': 'bosnian', 'bg': 'bulgarian', 'ca': 'catalan', 'ceb': 'cebuano', 'ny': 'chichewa', 'zh-cn': 'chinese (simplified)', 'zh-tw': 'chinese (traditional)', 'co': 'corsican', 'hr': 'croatian', 'cs': 'czech', 'da': 'danish', 'nl': 'dutch', 'en': 'english', 'eo': 'esperanto', 'et': 'estonian', 'tl': 'filipino', 'fi': 'finnish', 'fr': 'french', 'fy': 'frisian', 'gl': 'galician', 'ka': 'georgian', 'de': 'german', 'el': 'greek', 'gu': 'gujarati', 'ht': 'haitian creole', 'ha': 'hausa', 'haw': 'hawaiian', 'iw': 'hebrew', 'he': 'hebrew', 'hi': 'hindi', 'hmn': 'hmong', 'hu': 'hungarian', 'is': 'icelandic', 'ig': 'igbo', 'id': 'indonesian', 'ga': 'irish', 'it': 'italian', 'ja': 'japanese', 'jw': 'javanese', 'kn': 'kannada', 'kk': 'kazakh', 'km': 'khmer', 'ko': 'korean', 'ku': 'kurdish (kurmanji)', 'ky': 'kyrgyz', 'lo': 'lao', 'la': 'latin', 'lv': 'latvian', 'lt': 'lithuanian', 'lb': 'luxembourgish', 'mk': 'macedonian', 'mg': 'malagasy', 'ms': 'malay', 'ml': 'malayalam', 'mt': 'maltese', 'mi': 'maori', 'mr': 'marathi', 'mn': 'mongolian', 'my': 'myanmar (burmese)', 'ne': 'nepali', 'no': 'norwegian', 'or': 'odia', 'ps': 'pashto', 'fa': 'persian', 'pl': 'polish', 'pt': 'portuguese', 'pa': 'punjabi', 'ro': 'romanian', 'ru': 'russian', 'sm': 'samoan', 'gd': 'scots gaelic', 'sr': 'serbian', 'st': 'sesotho', 'sn': 'shona', 'sd': 'sindhi', 'si': 'sinhala', 'sk': 'slovak', 'sl': 'slovenian', 'so': 'somali', 'es': 'spanish', 'su': 'sundanese', 'sw': 'swahili', 'sv': 'swedish', 'tg': 'tajik', 'ta': 'tamil', 'te': 'telugu', 'th': 'thai', 'tr': 'turkish', 'uk': 'ukrainian', 'ur': 'urdu', 'ug': 'uyghur', 'uz': 'uzbek', 'vi': 'vietnamese', 'cy': 'welsh', 'xh': 'xhosa', 'yi': 'yiddish', 'yo': 'yoruba', 'zu': 'zulu'}
Can someone help here by explaning why this problem happened all of a sudden? It works just 30 minutes ago. It's weird it stopped working without changing anything.
According to the documentation googletrans, https://pypi.org/project/googletrans/, "is an unofficial library using the web API of translate.google.com".
They specifically state:
Due to limitations of the web version of google translate, this API does not guarantee that the library would work properly at all times (so please use this library if you don’t care about stability)
and suggest to use the official Google Translate API (click here).
For further reading I highly suggest the following sources:
GoogleTrans Python not translating
https://pypi.org/project/googletrans/
https://py-googletrans.readthedocs.io/en/latest/
If you decide to switch to the official API check out: https://cloud.google.com/translate/docs
I'm trying to flatten a json file using json_normalize in Python (Pandas), but being a noob at this I always seem to end up in a KeyError.
What I would like to achieve is a DataFrame with all the Plays in a game.
I've tried numerous variants of paths and prefixes, but no success. Googled a lot as well, but I'm still falling short.
What I would like to end up with is a DataFrame like:
period, time, type, player1, player2, xcord, ycord
import pandas as pd
import json
with open('PlayByPlay.json') as data_file:
data = json.load(data_file)
from pandas.io.json import json_normalize
records = json_normalize(data)
plays = records['data.game.plays.play'][0]
plays
Would generate
{'aoi': [8470324, 8473449, 8475158, 8475215, 8477499, 8477933],
'apb': [],
'as': 0,
'asog': 0,
'desc': 'Zack Kassian hit Kyle Okposo',
'eventid': 7,
'formalEventId': 'EDM7',
'hoi': [8471678, 8475178, 8475660, 8476454, 8476457, 8476472],
'hpb': [],
'hs': 0,
'hsog': 0,
'localtime': '5:12 PM',
'p1name': 'Zack Kassian',
'p2name': 'Kyle Okposo',
'p3name': '',
'period': 1,
'pid': 8475178,
'pid1': 8475178,
'pid2': 8473449,
'pid3': '',
'playername': 'Zack Kassian',
'strength': 701,
'sweater': '44',
'teamid': 22,
'time': '00:28',
'type': 'Hit',
'xcoord': 22,
'ycoord': 38}
Json
{'data': {'game': {'awayteamid': 7,
'awayteamname': 'Buffalo Sabres',
'awayteamnick': 'Sabres',
'hometeamid': 22,
'hometeamname': 'Edmonton Oilers',
'hometeamnick': 'Oilers',
'plays': {'play': [{'aoi': [8470324,
8473449,
8475158,
8475215,
8477499,
8477933],
'apb': [],
'as': 0,
'asog': 0,
'desc': 'Zack Kassian hit Kyle Okposo',
'eventid': 7,
'formalEventId': 'EDM7',
'hoi': [8471678, 8475178, 8475660, 8476454, 8476457, 8476472],
'hpb': [],
'hs': 0,
'hsog': 0,
'localtime': '5:12 PM',
'p1name': 'Zack Kassian',
'p2name': 'Kyle Okposo',
'p3name': '',
'period': 1,
'pid': 8475178,
'pid1': 8475178,
'pid2': 8473449,
'pid3': '',
'playername': 'Zack Kassian',
'strength': 701,
'sweater': '44',
'teamid': 22,
'time': '00:28',
'type': 'Hit',
'xcoord': 22,
'ycoord': 38},
{'aoi': [8471742, 8475179, 8475215, 8475220, 8475235, 8475728],
'apb': [],
'as': 0,
'asog': 0,
'desc': 'Jesse Puljujarvi Tip-In saved by Robin Lehner',
'eventid': 59,
'formalEventId': 'EDM59',
'hoi': [8473468, 8474034, 8475660, 8477498, 8477934, 8479344],
'hpb': [],
'hs': 0,
'hsog': 1,
'localtime': '5:13 PM',
'p1name': 'Jesse Puljujarvi',
'p2name': 'Robin Lehner',
'p3name': '',
'period': 1,
'pid': 8479344,
'pid1': 8479344,
'pid2': 8475215,
'pid3': '',
'playername': 'Jesse Puljujarvi',
'strength': 701,
'sweater': '98',
'teamid': 22,
'time': '01:32',
'type': 'Shot',
'xcoord': 81,
'ycoord': 3}]}},
'refreshInterval': 0}}
If you have only one game, this will create the dataframe you want:
json_normalize(data['data']['game']['plays']['play'])
Then you just need to extract the columns you're interested in.
it might be un-intuitive to use this API when the structure becomes complicated.
but the key is: json_normalize extracts JSON fields into table.
for my case: I have a table
----------
| fact | // each row is a json object {'a':a, 'b':b....}
----------
rrrrr = []
for index, row in data.iterrows():
r1 = json_normalize(row['fact'])
rrrrr.append(r1)
rr1 = pd.concat(rrrrr)
I have a dictionary in which I have to replace all the keys depending on a word in the value set. So my dictionary is:
{ 23: {'score': -8.639, 'char': False, 'word': 'positive'} }
{ 56: {'score': -5.6, 'char': False, 'word': 'neutral'} }
{ 89: {'score': -8.9, 'char': False, 'word': 'positive'} }
{ 34: {'score': -2.3, 'char': Tru, 'word': 'negative'} }
If the values part of dictionary i.e. the key word is positive then it should replace the key 23 with +1, for neutral's, the key 56 with 0 and for negative, the key 34 with -1.
The output will look like:
{ +1: {'score': -8.639, 'char': False, 'word': 'positive'} }
{ 0: {'score': -5.6, 'char': False, 'word': 'neutral'} }
{ +1: {'score': -8.9, 'char': False, 'word': 'positive'} }
{ -1: {'score': -2.3, 'char': Tru, 'word': 'negative'} }
Here is my code:
for n, line in enumerate(sys.stdin,1):
d = ast.literal_eval(line)
items = d.values()[0].items()
if re.match("positive",d.get('sentimentoftweet')):
n = str.replace(str(n),"+1")
else:
n = str.replace(str(n),"0")
Its not working and giving me this error:
Traceback (most recent call last):
File "./linear.py", line 33, in <module>
for thing in d:
File "./linear.py", line 22, in gen_with_appropriate_name
if re.match("positive",d.get('sentimentoftweet')):
File "/usr/lib/python2.7/re.py", line 137, in match
return _compile(pattern, flags).match(string)
TypeError: expected string or buffer
You're passing incorrect key to re.match. For missing key dict.get returns None, use d.get('word').
>>> import re
>>> re.match('foo', None)
Traceback (most recent call last):
File "<ipython-input-43-c75223170494>", line 1, in <module>
re.match('foo', None)
File "/usr/lib/python3.3/re.py", line 156, in match
return _compile(pattern, flags).match(string)
TypeError: expected string or buffer
You can match the strings or values using ==:
if d.get('word') == 'positive':
#do something
elif d.get('word') == 'negative'
#do something else
Code:
import sys, ast
for line in sys.stdin:
d = ast.literal_eval(line)
key = list(d)[0] #dictionary with just one key.
if d[key]['word'] == 'positive':
print {'+1': d[key]}
elif d[key]['word'] == 'negative':
print {'-1': d[key]}
elif d[key]['word'] == 'neutral':
print {'0': d[key]}
Output:
{'+1': {'char': False, 'score': -8.639, 'word': 'positive'}}
{'0': {'char': False, 'score': -5.6, 'word': 'neutral'}}
{'+1': {'char': False, 'score': -8.9, 'word': 'positive'}}
{'-1': {'char': True, 'score': -2.3, 'word': 'negative'}}
The problem is that d.get('word') is not looking inside the nested dictionary.
Perhaps something like this:
#!/usr/local/cpython-3.3/bin/python
import pprint
import collections
dict_ = { 23: {'score': -8.639, 'char': False, 'word': 'positive'},
56: {'score': -5.6, 'char': False, 'word': 'neutral'},
89: {'score': -8.9, 'char': False, 'word': 'positive'},
34: {'score': -2.3, 'char': True, 'word': 'negative'},
}
new_dict = collections.defaultdict(list)
for key, value in dict_.items():
if value['word'] == 'positive':
key = '+1'
elif value['word'] == 'neutral':
key = '0'
elif value['word'] == 'negative':
key = '-1'
else:
raise ValueError('word not positive, neutral or negative')
new_dict[key].append(value)
pprint.pprint(new_dict)