what is the best way to see if there is a range of keys in a dict? for example my dict will have keys from 1-20 and if i want to see if they're all populated or not. I know to use the 'in' keyword, it's the range part I'm having trouble finding
@AndrasDeak I would like too apologize for posting my question too many times. I am really sorry and my apologies for late reply ive been sick past few days. Just regarding to doing job, ive not been asking you to tell me to write code. See im a 3rd yr intern student and my reporting manager doesn't give any assistance.
Furthermore i do try before asking anything, but im very weak at programming. Thats why i ask questions here. Again i apologize for asking too many times. Sorry for causing inconvenience
Hi Can somebody help me? Pygame window is not opening, when I run my code by double clicking on it. But when I run it via Python Shell, everything works perfectly.
It's set to python. When I double click on the file, a little black window pops up with label 'py.exe', than immedietly close. And nothing else happening.
essentially, the bottom line is clear. there's a difference between the two ways of launching the app for some reason. i still suspect whether the .py file is set to the correct python executable on double click or not.
hello, I have the following json: {"my-value": 1, "my-second-value": 2}. How could I define a class to store these fields? I would like to resend later in the same format, but "-" is a reserved word. Thank you :)
It is perhaps the Java influence that makes you want to create the class in the first place. What exactly does your Flask app need to do with that JSON data?
@roganjosh it is better to have class definitions because I have many relationships among the classes and it is better for developers to access into attributes
@Aran-Fey I am doing a framework which other developers use it. I want to develop something easy for them which hide JSON conversion and also Flask communication
@ParitoshSingh yes, it is entirely under my control. Developers could need to send JSON fields with hypthen (for example, "Content-type"). My idea is to be in the middle, convert the JSON to the class, and viceversa
Content-type must be send as "Content-type" in the JSON, but I need to store it as field in a class...maybe...like "contentType"
You can provide a __setattr__ and __getattr__ that reference an aliases map:
class Dummy(object):
aliases = {
'xValue': 'x',
'another': 'x',
}
def __init__(self):
self.x = 17
def __setattr__(self, name, value):
name = self.aliases.get(name, n...
There are some really good comments explaining why allowing mindless aliasing is like a "niceness or luxury is an evil trap that will eventually cause more confusion than good. "
class Something:
def __init__(self, data):
self.data = data
def set_content_type(self, new_type):
self.data['content-type'] = new_type
In that case, you still have a class with defined methods, but the data is always in a form that is readily serialized back to JSON when you want to send it back out of Flask
^ Not helped by the fact that the "bug" pointed out implies that there's no fixed format of the incoming data
@pakkk In Flask you will likely have a request object, so you just use request.json and pass that to your class to now have a dictionary. When you want to send it back out, it would be jsonify(Something.data)
This is all assuming a flat dictionary. I mean, we haven't yet considered that JSON doesn't just have to be that and could be heavily nested with lists and dictionaries
I have a dataframe column with a list of words in each row....as you can see in the picture... I want to make a wordcloud picture...so i need all the words in all the tweets in a single string
i still don't really get what you're trying to do with the class here. if possible, assuming no one is sending a hyphen inside a json for your class, can you create an MCVE showing what you're trying to do?
In future, please also provide the code that constructs an example dataframe in addition to the code you're using to manipulate it. Based on what I can see in the screenshot, my example should be representative, at least in terms of 'a'
@pakk I agree with the others who are saying that converting JSON to a class structure is not a great idea. Apart from the problem of illegal chars in identifiers, the class structure can get really messy if you have deeply nested JSON.
I have a hard time conceptualising what the flask app actually does with the input. I can't see what useful things you might do with JSON that can have any valid key other than simple things like "multiply all values in this dict by 2" or something similarly indiscriminate
If the idea is that there will be at least some expected keys, and then an arbitrary number of other keys, then the whole business of a class is needless complexity - just keep everything else as dictionary keys
lst = df['Tweet_stopped'].values.tolist()
out = ' '.join([item for sublist in lst for item in sublist])
print ("There are {} words in the combination of all review.".format(len(out)))
lst = df['a'].values.tolist()
words = [item for sublist in lst for item in sublist]
out = ' '.join(words)
print ("There are {} words in the combination of all review.".format(len(words)))
@pakkk the way you describe the use cases, you don't have classes. You have dictionaries that you want accessed with attribute syntax instead of key syntax.
I'd like to define the framework for dummies. Give classes and nothing more. My framework will do the communication by Flask but developers do not care about that. They will only send/receive objects (classes), I will do everything for them
@pakkk If you have a complicated nested JSON which you load into a Python structure of dicts & lists, then you can easily traverse that data with recursive functions or generators. Traversing a complex dynamically created class structure would be a little harder: you'd essentially be doing the same thing with your classes __dict__, adding an extra layer that would make the code harder to read, and probably slower.
@EduardoGutierrez right, so the onus is on you to provide a representative DF example for me, because I can't do anything more from what you've provided
This is as you can watch in a column with all the words are in a string...now i have added columns to clean the words, i have deleted stopwords and tokenizer the string for further analysis
@pakkk FWIW, you may find my code here useful. It shows how to write recursive generators to traverse nested dicts & lists, presumably from JSON. Also see the code linked at the end of that answer.
Devil's advocate: if a developer needs to construct json that adheres to a complicated but well-defined structure, then it might make sense to provide classes corresponding to each layer of data so that you can validate the structure of the data as the developer creates it.
If the data represents a classroom of students that each belong to a family and each family owns zero or more vehicles, then maybe you benefit from writing Classroom, Student, Family, and Vehicle classes. Then there's no chance that the developer will send you data where little Bobby is the child of a Toyota Camry.
@Arne Certainly validation is the main goal of this hypothetical design. But perhaps there are other benefits that you wouldn't get out of a non-class-based validator.
anyone knows what happened to the New Mexico Tech tkinter online resource? infohost.nmt.edu/tcc/help/pubs/tkinter - the site is down for a few weeks niow.
@Kevin Fair point. But it sounds like pakkk's code is a general translator, designed to convert arbitrary JSON to a class, and also perform the reverse conversion. But I guess the caller of his code may call it with a class that specifies the structure they expect. OTOH, you could just as easily specify that structure using JSON itself. ;)
@AlperAyna That's not the purpose of numpy. Numpy deals with vectorization on lists, which are traditionally slow. Dictionary lookups are pretty-well optimised in CPython already
@PM2Ring Yeah, I don't think pakkk's desire for a general translator fits my use case. If you're not writing each class manually, then you don't have a lot of control over validation.
It wouldn't, other than me now saying "You really should consider moving to Python 3 because Python 2 is at the end of its supported life pretty soon" :)
@ReblochonMasque No. But I do remember having problems accessing it a few weeks ago. I did eventually find something, but I'm not sure where, maybe the Wayback Machine...
However a good start is making the existing code easier to transition over to python 3 by writing code that is compatible. use lots of future imports and stuff at the bare minimum perhaps.
@AlperAyna fair enough, I can't do much about your environment unfortunately. But just to check; your question implies a general thought of "numpy is faster"; you're not using numpy arrays as drop-in replacements for lists, are you? Like appending to arrays etc.?
@roganjosh I am not, I just try to make faster anything that I update. Try to improve every code I touch whenever I can. Never used numpy before, trying to use & test it if i can use.
@PM2Ring All of them internal code, worse thing is most of the author of these codes are not programmers originally so codes are terrible. Because of defensive issues and company issues, these are not available for all, never.
Oh dear... The New Mexico Tech site is the only one that could explain the Entry widget's text validation codes in a way that I could understand. I hope the page gets restored.
please don't try to improve performance with means you do not understand it is generally better to keep the code as high-level as performance permits that would, for example, fix most Py2/Py3 issues I have come across :/
So it's important to write code that is suited for numpy before doing any speed comparisons. And that means it's important to understand what exactly code "suited for numpy" would look like*
And by "explain in a way that I could understand" I mean "attempted to explain at all". The Tkinter handbook, for instance, doesn't even mention that they exist
Possibly I could reverse-engineer their meaning from the Tcl docs but translating Tcl to Tkinter has historically had a 25% success rate for me
@Kevin & @ReblochonMasque It looks like the NMT Python & Tkinter stuff is on Github: github.com/NMTCC Hopefully, they're just reorganizing their site...
Mildly annoyed that it's even possible in the first place for documentation to vanish because a third party site went down. Every other module gets to live in docs.python.org but tkinter is left out in the cold to fend for itself
@roganjosh as said before it worked in a column of text before cleaning... this was iterating all the column...text = " ".join(review for review in df['tweetText'])
print ("There are {} words in the combination of all review.".format(len(text))) gives There are 4077075 words in the combination of all review.
The data doesn't necessarily need to be on pastebin. But it does need to be smaller than half a GB. Try to create a representative sample that's smaller than 1 kb.
There are very few problems that require a million rows to demonstrate. Typically the same problem happens with a hundred rows too.
@RaphX Seriously, you should not be testing your code on the full 12GB data file! You should create a small file of a few kilobytes (at most) that contains sample data that can be used to test every feature of your code.
I have to go out for an hour or so so I won't be able to do anything on my phone now even if you do post an MCVE, but there's multiple people that might be able to help. In any case, please re-consider the link I posted and the comments above
@DeveshKumarSingh it just looped through keys to see if they were there. it was an if nested inside the for. if one wasn't present it returned 0, if all were there it started manipulating.
@roganjosh no worry i also have to go to have launch now... the code is easy for df[tweetText] which only have raw text... it gets complicated when using a list of words....thanks for your effort
sure it has to be easy... but im stuck....thanks for your help
@Kevin i have uploaded a 500 kb sample...of 500 tweets.....should be enough i think...
@EduardoGutierrez I guess that's small enough. How do I get the csv data into a dataframe? I tried df = pandas.DataFrame.from_csv("twitter_cleanedsample.csv") but then your code crashes with KeyError: 'a'
Never mind, I think from_csv works fine, I just pasted in the wrong code after that.
I do still want to see the code you're using to make the csv into a dataframe, just in case it works differently than from_csv, but I can poke around a little until then
@EduardoGutierrez, try pastebin.com/Bw6z8hmT. Short explanation: it's hard to count the number of words in your data because your data does not technically contain a list of words in any of its columns. Some columns look like a list of words, but they're still individual strings.
Possibly there is an option in pandas to automatically convert list-looking columns into actual lists. On the other hand, maybe there isn't, because I don't think I've ever seen a dataframe that contains nonscalar data.
Cbg! I have an issue, when I map to column in my df I lose all the values that are not contained in the dictionary of the mapping. Not sure how to go about this
just for reference, if someone tells me about "disk" I assume it to mean "HDD". Not "SSD" nor "Tape". For the later one would mean separate things with "Tape" or "Tape drive".
Interesting fact: bubble sort is ideal for a tape drive stackoverflow.com/a/3274203/344286 (or, when you can't hold a significant subset in memory, anyway)
@Kevin @roganjosh Im back again....Kevin id take a look to your answer but is strange because it should be a list of strings....here is a explanation how im cleaning the tweets....note in pass 0 i caculate in a easy way the number of words....
Man... I can't find it, maybe it's just M-Disc now, but I swear there was a service that you would just upload all of your media and they'd send you some kind of stone-based optical disc for long-term storage
But allegedly one guy decided to have a bit of fun with this and wrote code to time disk accesses in such a way as to maximize the rocking and to move the drive unit in a particular direction. He left his code running overnight, and when the operators arrived in the morning they couldn't get into the computer room because the drive was jammed up against the door.