Skip to content

Instantly share code, notes, and snippets.

@sysr-q
Last active December 11, 2015 02:09
Show Gist options
  • Save sysr-q/4528632 to your computer and use it in GitHub Desktop.
Save sysr-q/4528632 to your computer and use it in GitHub Desktop.
Explanation of some Python stuff for a guy on a forum.

THIS IS FOR YOU, Aura.

So, you said you want a file like this?

1-1234-60
2-23456-70
3-345678-80

These are your level, exp, whatever respectively.

I, however, would maybe suggest parsing it into JSON and then ending up with something like this instead:

{
  "info": {
		1: { "exp": 1234, "needed": 60 },
		2: { "exp": 2345, "needed": 70 },
		3: { "exp": 3456, "needed": 80 },
		# etc...
	}
}

Then you would have a dictionary which is easier to work with. You'd get that into a dictionary like this:

import json
levels = None
with open('levels.txt', 'rb') as f:
	levels = json.load(f)
print levels['info'][1] # shows: { "exp": 1234, "needed": 60 }
print levels['info'][1]['exp'] # shows: 1234
# etc...

This makes it much easier to work with, rather than a standard flat file layout.

quick note:

To save json, you simply do this:

my_dict = {
	"foo": "bar",
	"baz": "qux",
	"1": 7
}
with open('something.txt', 'wb') as f:
	json.dump(my_dict, f, indent=4) # indent so it looks good

So, onto your questions:

Question 1.

If I want to use text.split() on the FIRST LINE of a document, what is the exact syntax? If you use JSON, you don't have to split any strings!

yours = "1-1234-60".split('-')
print 'Level:', yours[0], 'exp:', yours[1], 'needed:', yours[2]

mine = {
	"info": {
		1: { "exp": 1234, "needed": 60 },
		# etc...
	}
}
level = 1
print 'Level:', level, 'exp:', mine['info'][level], 'needed:', mine['info'][level]

Isn't that much easier?

Question 2.

After when I get a string and use string.split() on it, example I do: "I love cats to 'I', 'love', 'cats'". How do I have to access these three words individually?

Usually, .split() gives you a list, which means you'll have to access them by their index. In your example:

cats = "I love cats"
cats_split = cats.split()
print cats_split # ['I', 'love', 'cats']
print cats_split[0] # 'I'
print cats_split[1] # 'love'
print cats_split[2], cats_split[0], cats_split[1] # cats I love

Question 3.

How can I do research in a document? Example, I enter the raw_input("Level:") and he enters 50. Which means he wants to info of the level 50 in Runescape. How can I reach this line containing the 50? What is the file research function? Like I mentioned earlier, with JSON this is easy.

levels = {
	# dictionary from file with all information
}
try:
	level = int(raw_input('Level: ')) # input: 1
	info = levels['info'][level]
	print info['exp'], info['needed'] # prints: 1234 60
except ValueError as e:
	print 'That is an invalid number, sorry.'

Tada!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment