How to insert a random element on a Anki card? - python
On Anki, the front of a card have "X+Y?" and the back shows "Z". For example, front "4+7?" and back "11" But I want next time that I see this card the numbers be different, randomizing the X, Y and Z elements. This could be possible picking the values from a pool previously defined by me, I guess.
Searching it on here, I found this code:
import random
foo = ['a', 'b', 'c', 'd', 'e']
print(random.choice(foo))
How can I put it to work on Anki? Because I just tried to copy it and paste in card model editor, but nothing happened. Sorry, I'm not a programmer, so I'd be grateful to know anything that can help me functionalize this random display. Thanks for your time.
Even though it is possible (but convoluted to make it happen), it is usually (very heavily) discouraged to make use of random content on Anki. The reason is the following: if some content has a change of being displayed at the front of a card, then it means you want to memorize it. But then, it means that you are bloating several things that you want to learn into a single card. For several reasons (among which: Anki is optimized to work with the assumption that each card corresponds to a single, atomic thing you want to learn. Breaking that assumption can only make it work worse, which in the end makes you spend more time trying to learn that stuff), it's better to just have a card for each possible thing you want to learn.
Edit having read my words of warning, I'll leave you judge of whether it's really a good decision to do what you want.
The first thing to understand is that even though Anki is mainly written in Rust and Python (which are two programming languages), and even though it supports add-ons written in Python, it's not Python (nor Rust) that should be used for this purpose. I say this because the snippet of code you provided is written in Python.
The reason behind this is that Anki uses webviews to render cards, which means that when you see a card, it's just like if you were seeing a website. Therefore, if you only want execute code when you are reviewing the cards (and not, say, automatically generate cards), the language you have to use is JavaScript. Unfortunately, I am not a JavaScript programmer, so my answer may suck. Fortunately, JavaScript is a rather simple programming language, very well documented, and your request is simple enough for me not to have much room to screw the code (meaning this answer should not suck too much). This being said, let's make it work:
Add a field to your notes that will hold the possible values that will be shown. To make it simple, let's assume none of these values will contain commas, so that we can simply write the values comma-separated. Let's say you called this field Values (rename it as you like). By default, it's going to pick the first of these values if it cannot pick at random. More on this at the end.
Now open the template edit window for this note. If you are in the browser, it should be the Cards... button.
Select Front Template (it should be selected by default). At the top of the template, add the following, which is code that will allow the randomly chosen value to be kept also when you reveal the answer (because by default it would just re-evaluate the whole script, picking at random again).
<script>
// v1.0.0 - https://github.com/SimonLammer/anki-persistence/blob/cd2ca88e019dc3b8f32dad623932c1eabdba7e21/script.js
if(void 0===window.Persistence){var _persistenceKey="github.com/SimonLammer/anki-persistence/",_defaultKey="_default";if(window.Persistence_sessionStorage=function(){var e=!1;try{"object"==typeof window.sessionStorage&&(e=!0,this.clear=function(){for(var e=0;e<sessionStorage.length;e++){var t=sessionStorage.key(e);0==t.indexOf(_persistenceKey)&&(sessionStorage.removeItem(t),e--)}},this.setItem=function(e,t){null==t&&(t=e,e=_defaultKey),sessionStorage.setItem(_persistenceKey+e,JSON.stringify(t))},this.getItem=function(e){return null==e&&(e=_defaultKey),JSON.parse(sessionStorage.getItem(_persistenceKey+e))},this.removeItem=function(e){null==e&&(e=_defaultKey),sessionStorage.removeItem(_persistenceKey+e)})}catch(e){}this.isAvailable=function(){return e}},window.Persistence_windowKey=function(e){var t=window[e],n=!1;"object"==typeof t&&(n=!0,this.clear=function(){t[_persistenceKey]={}},this.setItem=function(e,n){null==n&&(n=e,e=_defaultKey),t[_persistenceKey][e]=n},this.getItem=function(e){return null==e&&(e=_defaultKey),null==t[_persistenceKey][e]?null:t[_persistenceKey][e]},this.removeItem=function(e){null==e&&(e=_defaultKey),delete t[_persistenceKey][e]},null==t[_persistenceKey]&&this.clear()),this.isAvailable=function(){return n}},window.Persistence=new Persistence_sessionStorage,Persistence.isAvailable()||(window.Persistence=new Persistence_windowKey("py")),!Persistence.isAvailable()){var titleStartIndex=window.location.toString().indexOf("title"),titleContentIndex=window.location.toString().indexOf("main",titleStartIndex);titleStartIndex>0&&titleContentIndex>0&&titleContentIndex-titleStartIndex<10&&(window.Persistence=new Persistence_windowKey("qt"))}}
</script>
This code comes from anki persistance. Also, when editing templates, please do not write values above the snippet, always under (it won't change how it renders, but it will ensure all this code is loaded before you do anything else).
Select the Back Template, and add the following snippet at the top of the template (it's the same thing as before):
<script>
// v1.0.0 - https://github.com/SimonLammer/anki-persistence/blob/cd2ca88e019dc3b8f32dad623932c1eabdba7e21/script.js
if(void 0===window.Persistence){var _persistenceKey="github.com/SimonLammer/anki-persistence/",_defaultKey="_default";if(window.Persistence_sessionStorage=function(){var e=!1;try{"object"==typeof window.sessionStorage&&(e=!0,this.clear=function(){for(var e=0;e<sessionStorage.length;e++){var t=sessionStorage.key(e);0==t.indexOf(_persistenceKey)&&(sessionStorage.removeItem(t),e--)}},this.setItem=function(e,t){null==t&&(t=e,e=_defaultKey),sessionStorage.setItem(_persistenceKey+e,JSON.stringify(t))},this.getItem=function(e){return null==e&&(e=_defaultKey),JSON.parse(sessionStorage.getItem(_persistenceKey+e))},this.removeItem=function(e){null==e&&(e=_defaultKey),sessionStorage.removeItem(_persistenceKey+e)})}catch(e){}this.isAvailable=function(){return e}},window.Persistence_windowKey=function(e){var t=window[e],n=!1;"object"==typeof t&&(n=!0,this.clear=function(){t[_persistenceKey]={}},this.setItem=function(e,n){null==n&&(n=e,e=_defaultKey),t[_persistenceKey][e]=n},this.getItem=function(e){return null==e&&(e=_defaultKey),null==t[_persistenceKey][e]?null:t[_persistenceKey][e]},this.removeItem=function(e){null==e&&(e=_defaultKey),delete t[_persistenceKey][e]},null==t[_persistenceKey]&&this.clear()),this.isAvailable=function(){return n}},window.Persistence=new Persistence_sessionStorage,Persistence.isAvailable()||(window.Persistence=new Persistence_windowKey("py")),!Persistence.isAvailable()){var titleStartIndex=window.location.toString().indexOf("title"),titleContentIndex=window.location.toString().indexOf("main",titleStartIndex);titleStartIndex>0&&titleContentIndex>0&&titleContentIndex-titleStartIndex<10&&(window.Persistence=new Persistence_windowKey("qt"))}}
</script>
Go back to Front Template, and add the following where you want the value to be shown. If you don't know, just put it anywhere, check at the end where it renders well, and change it then, so you have visual feedback. Also avoid having other tags with id=values.
<div id="values">{{Values}}</div>
If you renamed the field Values, change the one between double braces too.
6. Add at the bottom of the template the following. This will be responsible for picking a value at random.
<script>
var valuesNode = document.getElementById("values");
var values = valuesNode.innerText.split(',');
var defaultValue = values[0];
var value = defaultValue;
if (Persistence.isAvailable()) {
value = Persistence.getItem();
if (value == null) {
value = values[Math.floor(Math.random() * values.length)];
Persistence.setItem(value);
}
}
valuesNode.innerText = value;
</script>
Go to the Back Template, and add the following where you want the value to be shown (just like in the front template):
<div id="values">{{Values}}</div>
At the bottom of the template, add the following. This will be responsible for showing the randomly picked value when showing the answer.
<script>
var valuesNode = document.getElementById("values");
var values = valuesNode.innerText.split(',');
var defaultValue = values[0];
var value = defaultValue;
if (Persistence.isAvailable()) {
value = Persistence.getItem();
Persistence.clear();
}
valuesNode.innerText = value;
</script>
Here I'm going to explain why there is a default value. This is due to the fact that several Anki clients handle JavaScript differently. anki persistance should work when you are reviewing, but it may not work when you are previewing a card. In these cases, it could still pick a random value, but when you would reveal the answer it could not "remember" which value it picked, so it would pick an other one at random. To prevent that, if it knows it will not remember, it will just pick the default one, so it's consistent when you reveal the answer.
Related
Dynamo Revit set formula for a parameter in a family
I am trying to add a formula to a parameter within a Revit Family. Currently I have multiple families in a project. I run Dynamo from within that project then I extract the families that I want to modify using Dynamo standard nodes. Then I use a python script node that goes through every selected family and find the parameter I am interested in, and assign a formula for it. That seemed fine until I noticed that it is not assigning the formula, but it is entering it as a string — as in it is in quotes. And sure enough, the code i am using will only work with Text type parameters. Can someone shed the light on how to assign a formula to a parameter using dynamo? see line 32 in code below Thanks for family in families: TransactionManager.Instance.ForceCloseTransaction() famdoc = doc.EditFamily(family) FamilyMan = famdoc.FamilyManager found.append(family.Name) TransactionManager.Instance.EnsureInTransaction(famdoc) check = 0 # Loop thru the list of parameters to assign formula values to them... these are given as imput for r in range(len(param_name_lst)): # Loop thru the list of parameters in the current family per the families outter loop above. for param in FamilyMan.Parameters: #for param in FamilyMan.get_Parameter(param_name_lst[r]): # for each of the parameters get their name and store in paramName. paramName = param.Definition.Name # Check if we have a match in parameter name. if param_name_lst[r] in paramName: if param.CanAssignFormula: canassignformula.append(param_name_lst[r]) else: cannotassignformula.append(param_name_lst[r]) try: # Make sure that the parameter is not locked. if FamilyMan.IsParameterLocked(param): FamilyMan.SetParameterLocked(param,False) locked.append(paraName) # Enter formula value to parameter. FamilyMan.SetFormula(param, param_value_lst[r]) check += 1 except: failed.append(paramName) else: continue
Actually, you can access the family from the main project, and you can assign a formula automatically.... That's what i currently do, i load all the families i want in one project and run the script. After a lot of work, i was able to figure out what i was doing wrong, and in it is not in my code... my code was fine. The main problem is that i need to have all of my formula's dependencies lined up.... just like in manual mode. so if my formula is: size_lookup(MY_ID_tbl, "MY_VAR", "MY_DefaultValue", ND1,ND2) then i need to have the following: MY_ID_tbl should exist and be assigned a valid value, in this case it should have a csv filename. Moreover, that file should be also loaded. This is important for the next steps. MY_VAR should be defined in that csv file, so Does ND1, ND2 The default value (My_Default_Value) should match what that csv file says about that variable...in this case, it is a text. Needless to say, i did not have all of the above lined up as it should be, once i fixed that, my setFormula code did its job. And i had to change my process altogether, cause i have to first create the MY_ID_tbl and load the csv file which i also do using dynamo, then i go and enter the formulas using dynamo.
Revit parameters can only be assigned to a formula inside the family editor only, that is the first point, so you should run your dynamo script inside the family editor for each family which will be a waste of time and you just edit the parameter's formula manually inside each family. and the second point, I don't even think that it is possible to set a certain parameter's formula automatically, it must be done manually ( I haven't seen anything for it in the Revit API docs).
Is there a way to remove items from various lists based on conditional statements?
I am writing a program that will act as a photography idea-generator for New York photographers. The way it works now is quite simple, the code is utilizing the random.choice function to randomly pull items from lists, then the code prints them out in a way that forms a sentence in English as an end result. My issue is I need to add some logic to this, as some results would not make sense for a photographer to do (at least in my opinion). In this example I am trying to remove 'Bracketed (HDR)' from the technique_list, IF "Portrait" happens to be randomly chosen when python chooses the theme item. I have a feeling I am mis-using the .remove function within the conditional if statement. Is there a better way to do this? I have attached the pertinent parts of the code for examination. I have tried technique_list.remove('Bracketed (HDR)') , as well as del technique_list[0] , both as the response part of the if statement. import random print ("You should try taking a...") #pool of items that the program will randomly choose.. theme_list = ['Cityscape','Peoplescape','Port-Scape', 'Portrait'] technique_list = ['Bracketed (HDR)','Wide Angle', 'Zoom','Long Exposure','Fast Shutter','Daytime Long Expo','Timelapse'] #what we need here are conditional IF statements, that manipulate items from various lists #this bit of code determines the theme of a photo idea theme_var = random.choice(theme_list) for theme in theme_var: if theme == 'Portrait': technique_list.remove('Bracketed (HDR)') print("",theme_var) #this bit of code determines the technique of a photo idea technique_var = random.choice(technique_list) print("", technique_var) print("picture, from") #this line of code determines the location of a photo idea location_var = random.choice(location_list) print("", location_var) This still remains one of the possible results of the code: You should try taking a... Portrait Bracketed (HDR) picture, from 34th Street during Sunrise and then give it a Black & White edit in Lightroom! [Finished in 0.2 As I said earlier, Portrait and Bracketed (HDR) should never be part of the same result, it doesn't make sense for this situation.
The issue (I think) is because you are iterating over the randomly chosen result not the list itself, you don't need the for loop that is. theme_var = random.choice(theme_list) if theme_var == 'Portrait': technique_list.remove('Bracketed (HDR)') print("",theme_var) #this bit of code determines the technique of a photo idea technique_var = random.choice(technique_list) print("", technique_var) print("picture, from") #rest of the code Should do it
I'd go with a dictionary of inappropriate techniques, a list comprehension, and top it off with an f-string: import random #pool of items that the program will randomly choose.. theme_list = ['Cityscape','Peoplescape','Port-Scape', 'Portrait'] technique_list = ['Bracketed (HDR)','Wide Angle', 'Zoom','Long Exposure','Fast Shutter','Daytime Long Expo','Timelapse'] location_list = ['34th Street'] # dictionary of inappropriate techniques for given theme d_inappropes = {'Cityscape': [], 'Port-Scape': [], 'Portrait': ['Bracketed (HDR)'], 'Peoplescape': ['Long Exposure', 'Timelapse', 'Daytime Long Expo']} #this bit of code determines the theme of a photo idea theme_var = random.choice(theme_list) #this bit of code determines the technique of a photo idea # list comprehension generates a new list with the inappropriate techniques removed, # without affecting the original list technique_var = random.choice([ti for ti in technique_list if ti not in d_inappropes[theme_var]]) #this line of code determines the location of a photo idea location_var = random.choice(location_list) # use f-stirngs to put the whole output in a single line to keep it managable print(f"You should try taking a \n {theme_var} {technique_var} picture, \n from {location_var}.")
if I may add and give more explanation to the answers You want to delete "bracked (HDR)" IF potrait is selected. Don't use .remove as it will delete "bracked (HDR)" permanently and prevent other theme to use that technique. you can use dictionary of inappropriate technique as kingfischer suggested for that random.choice outputted a single value from your list. you should not use for-loop with it as for-loop will iterate over the character/alphabets in the value outputted by random.choice if I may give a feedback, the indentations in your code snippet are quite jumbled. Some lines that should have indentation, don't have it. I don't know.. maybe it is unintended and the problem is with my browser. if it was so, sorry!
Python- Insert new values into 'nested' list?
What I'm trying to do isn't a huge problem in php, but I can't find much assistance for Python. In simple terms, from a list which produces output as follows: {"marketId":"1.130856098","totalAvailable":null,"isMarketDataDelayed":null,"lastMatchTime":null,"betDelay":0,"version":2576584033,"complete":true,"runnersVoidable":false,"totalMatched":null,"status":"OPEN","bspReconciled":false,"crossMatching":false,"inplay":false,"numberOfWinners":1,"numberOfRunners":10,"numberOfActiveRunners":8,"runners":[{"status":"ACTIVE","ex":{"tradedVolume":[],"availableToBack":[{"price":2.8,"size":34.16},{"price":2.76,"size":200},{"price":2.5,"size":237.85}],"availableToLay":[{"price":2.94,"size":6.03},{"price":2.96,"size":10.82},{"price":3,"size":33.45}]},"sp":{"nearPrice":null,"farPrice":null,"backStakeTaken":[],"layLiabilityTaken":[],"actualSP":null},"adjustmentFactor":null,"removalDate":null,"lastPriceTraded":null,"handicap":0,"totalMatched":null,"selectionId":12832765}... All I want to do is add in an extra field, containing the 'runner name' in the data set below, into each of the 'runners' sub lists from the initial data set, based on selection_id=selectionId. So initially I iterate through the full dataset, and then create a separate list to get the runner name from the runner id (I should point out that runnerId===selectionId===selection_id, no idea why there are multiple names are used), this works fine and the code is shown below: for market_book in market_books: market_catalogues = trading.betting.list_market_catalogue( market_projection=["RUNNER_DESCRIPTION", "RUNNER_METADATA", "COMPETITION", "EVENT", "EVENT_TYPE", "MARKET_DESCRIPTION", "MARKET_START_TIME"], filter=betfairlightweight.filters.market_filter( market_ids=[market_book.market_id], ), max_results=100) data = [] for market_catalogue in market_catalogues: for runner in market_catalogue.runners: data.append( (runner.selection_id, runner.runner_name) ) So as you can see I have the data in data[], but what I need to do is add it to the initial data set, based on the selection_id. I'm more comfortable with Php or Javascript, so apologies if this seems a bit simplistic, but the code snippets I've found on-line only seem to assist with very simple Python lists and nothing 'nested' (to me the structure seems similar to a nested array). As per the request below, here is the full list: {"marketId":"1.130856098","totalAvailable":null,"isMarketDataDelayed":null,"lastMatchTime":null,"betDelay":0,"version":2576584033,"complete":true,"runnersVoidable":false,"totalMatched":null,"status":"OPEN","bspReconciled":false,"crossMatching":false,"inplay":false,"numberOfWinners":1,"numberOfRunners":10,"numberOfActiveRunners":8,"runners":[{"status":"ACTIVE","ex":{"tradedVolume":[],"availableToBack":[{"price":2.8,"size":34.16},{"price":2.76,"size":200},{"price":2.5,"size":237.85}],"availableToLay":[{"price":2.94,"size":6.03},{"price":2.96,"size":10.82},{"price":3,"size":33.45}]},"sp":{"nearPrice":null,"farPrice":null,"backStakeTaken":[],"layLiabilityTaken":[],"actualSP":null},"adjustmentFactor":null,"removalDate":null,"lastPriceTraded":null,"handicap":0,"totalMatched":null,"selectionId":12832765},{"status":"ACTIVE","ex":{"tradedVolume":[],"availableToBack":[{"price":20,"size":3},{"price":19.5,"size":26.36},{"price":19,"size":2}],"availableToLay":[{"price":21,"size":13},{"price":22,"size":2},{"price":23,"size":2}]},"sp":{"nearPrice":null,"farPrice":null,"backStakeTaken":[],"layLiabilityTaken":[],"actualSP":null},"adjustmentFactor":null,"removalDate":null,"lastPriceTraded":null,"handicap":0,"totalMatched":null,"selectionId":12832767},{"status":"ACTIVE","ex":{"tradedVolume":[],"availableToBack":[{"price":11,"size":9.75},{"price":10.5,"size":3},{"price":10,"size":28.18}],"availableToLay":[{"price":11.5,"size":12},{"price":13.5,"size":2},{"price":14,"size":7.75}]},"sp":{"nearPrice":null,"farPrice":null,"backStakeTaken":[],"layLiabilityTaken":[],"actualSP":null},"adjustmentFactor":null,"removalDate":null,"lastPriceTraded":null,"handicap":0,"totalMatched":null,"selectionId":12832766},{"status":"ACTIVE","ex":{"tradedVolume":[],"availableToBack":[{"price":48,"size":2},{"price":46,"size":5},{"price":42,"size":5}],"availableToLay":[{"price":60,"size":7},{"price":70,"size":5},{"price":75,"size":10}]},"sp":{"nearPrice":null,"farPrice":null,"backStakeTaken":[],"layLiabilityTaken":[],"actualSP":null},"adjustmentFactor":null,"removalDate":null,"lastPriceTraded":null,"handicap":0,"totalMatched":null,"selectionId":12832769},{"status":"ACTIVE","ex":{"tradedVolume":[],"availableToBack":[{"price":18.5,"size":28.94},{"price":18,"size":5},{"price":17.5,"size":3}],"availableToLay":[{"price":21,"size":20},{"price":23,"size":2},{"price":24,"size":2}]},"sp":{"nearPrice":null,"farPrice":null,"backStakeTaken":[],"layLiabilityTaken":[],"actualSP":null},"adjustmentFactor":null,"removalDate":null,"lastPriceTraded":null,"handicap":0,"totalMatched":null,"selectionId":12832768},{"status":"ACTIVE","ex":{"tradedVolume":[],"availableToBack":[{"price":4.3,"size":9},{"price":4.2,"size":257.98},{"price":4.1,"size":51.1}],"availableToLay":[{"price":4.4,"size":20.97},{"price":4.5,"size":30},{"price":4.6,"size":16}]},"sp":{"nearPrice":null,"farPrice":null,"backStakeTaken":[],"layLiabilityTaken":[],"actualSP":null},"adjustmentFactor":null,"removalDate":null,"lastPriceTraded":null,"handicap":0,"totalMatched":null,"selectionId":12832771},{"status":"ACTIVE","ex":{"tradedVolume":[],"availableToBack":[{"price":24,"size":6.75},{"price":23,"size":2},{"price":22,"size":2}],"availableToLay":[{"price":26,"size":2},{"price":27,"size":2},{"price":28,"size":2}]},"sp":{"nearPrice":null,"farPrice":null,"backStakeTaken":[],"layLiabilityTaken":[],"actualSP":null},"adjustmentFactor":null,"removalDate":null,"lastPriceTraded":null,"handicap":0,"totalMatched":null,"selectionId":12832770},{"status":"ACTIVE","ex":{"tradedVolume":[],"availableToBack":[{"price":5.7,"size":149.33},{"price":5.5,"size":29.41},{"price":5.4,"size":5}],"availableToLay":[{"price":6,"size":85},{"price":6.6,"size":5},{"price":6.8,"size":5}]},"sp":{"nearPrice":null,"farPrice":null,"backStakeTaken":[],"layLiabilityTaken":[],"actualSP":null},"adjustmentFactor":null,"removalDate":null,"lastPriceTraded":null,"handicap":0,"totalMatched":null,"selectionId":10064909}],"publishTime":1551612312125,"priceLadderDefinition":{"type":"CLASSIC"},"keyLineDescription":null,"marketDefinition":{"bspMarket":false,"turnInPlayEnabled":false,"persistenceEnabled":false,"marketBaseRate":5,"eventId":"28180290","eventTypeId":"2378961","numberOfWinners":1,"bettingType":"ODDS","marketType":"NONSPORT","marketTime":"2019-03-29T00:00:00.000Z","suspendTime":"2019-03-29T00:00:00.000Z","bspReconciled":false,"complete":true,"inPlay":false,"crossMatching":false,"runnersVoidable":false,"numberOfActiveRunners":8,"betDelay":0,"status":"OPEN","runners":[{"status":"ACTIVE","sortPriority":1,"id":10064909},{"status":"ACTIVE","sortPriority":2,"id":12832765},{"status":"ACTIVE","sortPriority":3,"id":12832766},{"status":"ACTIVE","sortPriority":4,"id":12832767},{"status":"ACTIVE","sortPriority":5,"id":12832768},{"status":"ACTIVE","sortPriority":6,"id":12832770},{"status":"ACTIVE","sortPriority":7,"id":12832769},{"status":"ACTIVE","sortPriority":8,"id":12832771},{"status":"LOSER","sortPriority":9,"id":10317013},{"status":"LOSER","sortPriority":10,"id":10317010}],"regulators":["MR_INT"],"countryCode":"GB","discountAllowed":true,"timezone":"Europe\/London","openDate":"2019-03-29T00:00:00.000Z","version":2576584033,"priceLadderDefinition":{"type":"CLASSIC"}}}
i think i understand what you are trying to do now first hold your data as a python object (you gave us a json object) import json my_data = json.loads(my_json_string) for item in my_data['runners']: item['selectionId'] = [item['selectionId'], my_name_here] the thing is that my_data['runners'][i]['selectionId'] is a string, unless you want to concat the name and the id together, you should turn it into a list or even a dictionary each item is a dicitonary so you can always also a new keys to it item['new_key'] = my_value
So, essentially this works...with one exception...I can see from the print(...) in the loop that the attribute is updated, however what I can't seem to do is then see this update outside the loop. mkt_runners = [] for market_catalogue in market_catalogues: for r in market_catalogue.runners: mkt_runners.append((r.selection_id, r.runner_name)) for market_book in market_books: for runner in market_book.runners: for x in mkt_runners: if runner.selection_id in x: setattr(runner, 'x', x[1]) print(market_book.market_id, runner.x, runner.selection_id) print(market_book.json()) So the print(market_book.market_id.... displays as expected, but when I print the whole list it shows the un-updated version. I can't seem to find an obvious solution, which is odd, as it seems like a really simple thing (I tried messing around with indents, in case that was the problem, but it doesn't seem to be, its like its not refreshing the market_book list post update of the runners sub list)!
Basics of connecting python to the web and validating user input
I'm relatively new, and I'm just at a loss as to where to start. I don't expect detailed step-by-step responses (though, of course, those are more than welcome), but any nudges in the right direction would be greatly appreciated. I want to use the Gutenberg python library to select a text based on a user's input. Right now I have the code: from gutenberg.acquire import load_etext from gutenberg.cleanup import strip_headers text = strip_headers(load_etext(11)).strip() where the number represents the text (in this case 11 = Alice in Wonderland). Then I have a bunch of code about what to do with the text, but I don't think that's relevant here. (If it is let me know and I can add it). Basically, instead of just selecting a text, I want to let the user do that. I want to ask the user for their choice of author, and if Project Gutenberg (PG) has pieces by that author, have them then select from the list of book titles (if PG doesn't have anything by that author, return some response along the lines of "sorry, don't have anything by $author_name, pick someone else." And then once the user has decided on a book, have the number corresponding to that book be entered into the code. I just have no idea where to start in this process. I know how to handle user input, but I don't know how to take that input and search for something online using it. Ideally, I'd be able to handle things like spelling mistakes too, but that may be down the line. I really appreciate any help anyone has the time to give. Thanks!
The gutenberg module includes facilities for searching for a text by metadata, such as author. The example from the docs is: from gutenberg.query import get_etexts from gutenberg.query import get_metadata print(get_metadata('title', 2701)) # prints frozenset([u'Moby Dick; Or, The Whale']) print(get_metadata('author', 2701)) # prints frozenset([u'Melville, Hermann']) print(get_etexts('title', 'Moby Dick; Or, The Whale')) # prints frozenset([2701, ...]) print(get_etexts('author', 'Melville, Hermann')) # prints frozenset([2701, ...]) It sounds as if you already know how to read a value from the user into a variable, and replacing the literal author in the above would be as simple as doing something like: author_name = my_get_input_from_user_function() texts = get_etexts('author', author_name) Note the following note from the same section: Before you use one of the gutenberg.query functions you must populate the local metadata cache. This one-off process will take quite a while to complete (18 hours on my machine) but once it is done, any subsequent calls to get_etexts or get_metadata will be very fast. If you fail to populate the cache, the calls will raise an exception. With that in mind, I haven't tried the code I've presented in this answer because I'm still waiting for my local cache to populate.
Using Strings to Name Hash Keys?
I'm working through a book called "Head First Programming," and there's a particular part where I'm confused as to why they're doing this. There doesn't appear to be any reasoning for it, nor any explanation anywhere in the text. The issue in question is in using multiple-assignment to assign split data from a string into a hash (which doesn't make sense as to why they're using a hash, if you ask me, but that's a separate issue). Here's the example code: line = "101;Johnny 'wave-boy' Jones;USA;8.32;Fish;21" s = {} (s['id'], s['name'], s['country'], s['average'], s['board'], s['age']) = line.split(";") I understand that this will take the string line and split it up into each named part, but I don't understand why what I think are keys are being named by using a string, when just a few pages prior, they were named like any other variable, without single quotes. The purpose of the individual parts is to be searched based on an individual element and then printed on screen. For example, being able to search by ID number and then return the entire thing. The language in question is Python, if that makes any difference. This is rather confusing for me, since I'm trying to learn this stuff on my own. My personal best guess is that it doesn't make any difference and that it was personal preference on part of the authors, but it bewilders me that they would suddenly change form like that without it having any meaning, and further bothers me that they don't explain it. EDIT: So I tried printing the id key both with and without single quotes around the name, and it worked perfectly fine, either way. Therefore, I'd have to assume it's a matter of personal preference, but I still would like some info from someone who actually knows what they're doing as to whether it actually makes a difference, in the long run. EDIT 2: Apparently, it doesn't make any sense as to how my Python interpreter is actually working with what I've given it, so I made a screen capture of it working https://www.youtube.com/watch?v=52GQJEeSwUA
I don't understand why what I think are keys are being named by using a string, when just a few pages prior, they were named like any other variable, without single quotes The answer is right there. If there's no quote, mydict[s], then s is a variable, and you look up the key in the dict based on what the value of s is. If it's a string, then you look up literally that key. So, in your example s[name] won't work as that would try to access the variable name, which is probably not set. EDIT: So I tried printing the id key both with and without single quotes around the name, and it worked perfectly fine, either way. That's just pure luck... There's a built-in function called id: >>> id <built-in function id> Try another name, and you'll see that it won't work.
Actually, as it turns out, for dictionaries (Python's term for hashes) there is a semantic difference between having the quotes there and not. For example: s = {} s['test'] = 1 s['othertest'] = 2 defines a dictionary called s with two keys, 'test' and 'othertest.' However, if I tried to do this instead: s = {} s[test] = 1 I'd get a NameError exception, because this would be looking for an undefined variable called test whose value would be used as the key. If, then, I were to type this into the Python interpreter: >>> s = {} >>> s['test'] = 1 >>> s['othertest'] = 2 >>> test = 'othertest' >>> print s[test] 2 >>> print s['test'] 1 you'll see that using test as a key with no quotes uses the value of that variable to look up the associated entry in the dictionary s. Edit: Now, the REALLY interesting question is why using s[id] gave you what you expected. The keyword "id" is actually a built-in function in Python that gives you a unique id for an object passed as its argument. What in the world the Python interpreter is doing with the expression s[id] is a total mystery to me. Edit 2: Watching the OP's Youtube video, it's clear that he's staying consistent when assigning and reading the hash about using id or 'id', so there's no issue with the function id as a hash key somehow magically lining up with 'id' as a hash key. That had me kind of worried for a while.