104 Posted Topics
Re: If I understand you correctly, you want to substitute the "VALUE" of a residence feature which would be a "KEY" in a dictionary. For each different value, there will be a different key. A dictionary is perfect for this. Example:[code=Python]# features = open('features.txt').read() features = '''1701|RES|HVAC|Central Air 1702|RES|HVAC|Window Unit 1703|RES|HVAC|Heat … | |
Re: Try stripping leading and trailing whitespace. Add [I]lines.strip().[/I] in front of [I]endswith[/I]. [code=Python]if lines.strip().startswith('%s' % get) and lines.strip().endswith("%s" % tags['%s' % get]):[/code] | |
Re: A general solution: [code=Python]def str_to_int(s): return int(''.join([c for c in s if c in '1234567890'])) s = '105 mV' print str_to_int(s)[/code] | |
Re: #2 I am not sure, but methods crop() and rotate() should return image objects. If so, you could simply:[code=Python]for n in range(1, 4): im1 = im1.rotate(90).crop(box) im1.save("screen%s.jpg" % n)[/code] | |
Re: Sometimes it's easier to show some code: [code=Python]import time, datetime data = '2008-10-27 12:05:54' fmt = '%Y-%m-%d %H:%M:%S' ts1 = time.strptime(data, fmt) dt1 = datetime.datetime(*time.strptime(data, fmt)[:6]) dt2 = datetime.datetime(*time.strptime(data, fmt)[:6])+datetime.timedelta(minutes=45) print "%s:%s:%s" % (dt2.hour, dt2.minute, dt2.second)[/code] Output: [code=Python]>>> 12:50:54[/code] | |
Re: You must close the file object to flush the output buffers. You can manually flush the buffers with file method [I]flush()[/I]. | |
Re: [I]random.sample()[/I] may be what you are looking for. [code=Python]>>> let = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g' ] >>> random.sample(let,len(let)) ['a', 'd', 'g', 'b', 'c', 'f', 'e'] >>> random.sample(let,3) ['d', 'e', 'b'] >>> random.sample(let,3) ['a', 'f', 'e'] >>> [/code] | |
Re: You can also use [I]getattr()[/I] on class and instance objects. Examples: [code=Python]>>> Plane3D <class '__main__.Plane3D'> >>> getattr(Plane3D, 'ThreePtCircle', None) <unbound method Plane3D.ThreePtCircle> >>> plane1 = Plane3D(Point(0,0,0), Point(1,0,0), Point(0,1,0)) >>> getattr(plane1, 'ThreePtCircle') <bound method Plane3D.ThreePtCircle of Plane3D(Point(0.000000, 0.000000, 0.000000), Point(1.000000, 0.000000, 0.000000), Point(0.000000, 1.000000, 0.000000), theta=1.570796)> >>> [/code] | |
Re: You should not look at the permutations for this problem, you should look at the [I]rotations[/I].[code]def rotations(s): return [s[i:]+s[:-len(s)+i] for i in range(len(s))] [/code]Example: >>> rotations('87321') ['87321', '73218', '32187', '21873', '18732'] >>> | |
Re: I posted to a similar thread recently, but I can't remember where. The following will preserve punctuation:[code=Python]from string import punctuation as stuff def words_between(s, first, second): # return the words between first and second words words = [word.lower() for word in s.split()] # catch error if word not in sentence … | |
Re: [QUOTE=paulthom12345;711332]that just makes sure the program knows where to look to find the variables. So if more than one thing was in the formatted string you would use a tuple.[/QUOTE] It's required to enclose the variable in parentheses in this case:[code=Python]>>> a = 5 >>> b = 10 >>> print … | |
Re: The substring "\t" in [I]string[/I] is evaluated as a tab character. The [I]re[/I] method [I]match[/I] only matches at the beginning of a string. Try this: [code=Python]import re s = r'c:\test.doc' m = re.search(r":(\\[0-9a-z])", s) if m: print m.group(1) else: print m[/code] | |
Re: The following splits the sentence up into words first, looks for the index of word 1, then looks for the index of word 2 starting after index 1. Punctuation and whitespace is stripped from each word.[code=Python]import string def words_between(s, first, second): # return the words between first and second words … | |
Re: Do not use [I]sum[/I] as a variable name, because it is a built in function. I would suggest that you not use [I]split[/I] either, because it is confusing (it is to me anyway). Use [I]sum()[/I] and [I]len()[/I] to return your values.[code]def line_sum_and_count(line): """Finds the sum and count of the numbers … | |
Re: Not to be picky, but an iterable can be converted to a list with the built-in function [I]list[/I]. [code]>>> import string >>> list(string.letters) ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', … | |
Re: [QUOTE=knish;697224]i am using glob.glob('') function to get a list of all files from a folder. I need to get only those names which do not contain '_ab' in it. How is it possible. I understand the need for regular expressions here. i tried (?!....) . what should work here. example … | |
Re: Use string method [I]strip()[/I] to remove newline characters. [code=Python]for line in lines: filemenu.add_cascade(label=line.strip())[/code] | |
![]() | Re: Decide what types of objects that need to be converted. If needed, create a function to make each conversion type. An exception should occur on any failed conversion. If all conversions fail, return a string. Example: [code=Python]import time def fdim(s): # return a float given a fraction (EX. '1/2') ss … |
Re: You can use escape sequence [I]\b[/I] to match exact words. [code]import re s = "I'm trying to debug a problem but the debugger is not working" target = 'debug' repl = 'fix' patt = re.compile(r'\b%s\b' % target) print patt.sub(repl, s)[/code]Gribouillis has a very nice solution. I am going to use … | |
Re: File method [U]readline()[/U] reads an entire line from an open file at the file's current position. The file position is relocated. File method [I]tell()[/I] returns the current position. Example:[code]>>> f = open(r'D:\SDS2_7.0\macro\Work In Progress\line_numbers.txt') >>> f.tell() 0L >>> f.readline() 'Line 1\n' >>> f.tell() 8L >>> f.readline() 'Line 2\n' >>> f.tell() … | |
Re: This seems to work: [code=Python]t = 'I love cheese; cheese is my favourite besides melted cheese.' cheeses = ["shredded gorgonzola","bree","camenbert"] for s in cheeses: t = t.replace('cheese', s, 1)[/code]Here's another way using the string method [I]index()[/I] and slicing:[code=Python]def str_sub_multiple(s, target, sub_list): for sub in sub_list: try: n = s.index(target) s … | |
Re: Since I am using Python 2.3, I will define a function to pass to [I]sort()[/I]. [code=Python]def comp(a,b): return cmp(a[5], b[5]) f = open('sample_data.txt') data_list = [[float(item) for item in line.strip().split(',')] for line in f] data_list.sort(comp) f.close()[/code]When you read the information from file, each line is a string as in:[code=Python]"4, 8, … | |
Re: Every XML document must have a declaration and a root element. I may do something like this:[code]data = """ndoe bali swimming male""" tag_list = ['name', 'home', 'hobby', 'gender'] xml_data_list = ['<?xml version="1.0" encoding="ISO-8859-1"?>','<people>'] for i, item in enumerate(data.split()): xml_data_list.append("<%s>%s</%s>" % (tag_list[i], item, tag_list[i])) xml_data_list.append('</people>') print '\n'.join(xml_data_list)[/code] Output: >>> <?xml version="1.0" … | |
Re: You don't need regex for this: [code]>>> array = ['red','blue'] >>> array1 = [' %s ' % item for item in array] >>> array1 [' red ', ' blue '] >>> [/code] | |
Re: [QUOTE=fmv2011;659006]I indeed do get the same error. I am using version 2.2.3. Is there any way for me to get around this?[/QUOTE]The following works in Python 2.3 and may work in 2.2.[code=Python]alist = [1,3,2,5,4,7,6] alist.sort() alist.reverse()[/code]Note that methods sort() and reverse() reorder list object alist in place. | |
Re: My thought was to do something like the following:[code=Python]data = '''Date Open High Low Close Volume Adj 7/18/2008 19.57 20.1 17.76 19.11 50773900 19.11 7/17/2008 18.08 20.15 16.81 18.9 72725600 18.9 7/16/2008 14.27 16.85 13.47 16.65 83402200 16.65 7/15/2008 12.99 14.58 12.02 13.22 132443700 13.22 7/14/2008 16.25 16.3 12.4 12.4 … | |
Re: By adding a __cmp__ method to class [I]Movie[/I], you can sort instance objects in list [I]m1[/I] with list method [I]sort()[/I]. Following is an example of a __cmp__ overload in a Vector class that sorts on the x, y and z attributes: [code=Python] def __cmp__(self, other, epsilon=0.000001): x = abs(self.x-other.x) if … | |
Re: You can use string formatting for your regex pattern. The following iterates on the file object. For the top 10 players, variable [I]data[/I] should have 40 items. Match object m.groups() should have 5 items. The first item will be the entire matched string. The data you are interested in will … | |
Re: It appears that you omitted an operator: yIntercept = y1 - (((y2 - y1)/(x2 - x1))[B][COLOR="Red"](add operator here)[/COLOR][/B](x1)) | |
Re: Function indexList() returns a list of indices of '-' in the string. Function strip_chrs() strips the trailing characters from the first occurrence of a letter after the last '-'.[code=Python]def indexList(s, item, i=0): """ Return an index list of all occurrances of 'item' in string/list 's'. Optional start search position 'i' … | |
Re: Convert the integers to strings with a list comprehension and use string method join() to combine:[code=Python]>>> a=[0,1,2,3,4] >>> print ''.join([str(i) for i in a]) 01234 >>> [/code] | |
Re: You are returning a tuple in cun_to_centimeters(). Access the elements of the tuple by slicing. Example: [code=Python]>>> def ret_tuple(): ... return 1, 2 ... >>> obj = ret_tuple() >>> obj[0] 1 >>> obj[1] 2 >>> [/code] | |
Re: [code]>>> s = 'XXXXX -\n\t XXXX' >>> ''.join(s.split()) 'XXXXX-XXXX' >>> [/code] | |
Re: The string method splitlines() can preserve trailing newlines.[code]>>> string.splitlines(1) ['Hello\n', 'World'] >>> [/code] | |
Re: Here is an example using woooee's suggestion: [code]s = '''ABCD vvvv 1e-12 ABCD hhhh 1e-6 ABCD ggggg 1e-3 ASDE ffffff 1e-57 ASDE dddd 0.001''' dd = {} for item in s.split('\n'): itemList = item.split() if itemList[0] in dd: if float(dd[itemList[0]][1]) > float(itemList[2]): dd[itemList[0]] = itemList[1:] else: dd[itemList[0]] = itemList[1:] for … | |
Re: The other solutions offered work fine. If you want to use a regular expression, the following may work also:[code=Python]import re patt = re.compile(r'call +(?!%\S+%)') print patt.match('call %_junk% text1') print patt.match('call GetFiles %Label%')[/code]This matches the word 'call' at the beginning of the line followed by any number of spaces if not … | |
Re: >>> s = 'airplane' >>> list(s) ['a', 'i', 'r', 'p', 'l', 'a', 'n', 'e'] >>> | |
Re: Try this: [code=Python]filters = {'small': DateFormat.small, 'big': DateFormat.big}[/code] This works in Python 2.3:[code=Python] import sys class DateFormat(object): """Class to format and translate date to polish""" labels = { 'monday' : u'poniedziaÅ‚ek', 'tuesday' : u'wtorek', 'wenesday' : u'Å›roda', 'thursday' : u'czwartek', 'friday' : u'piÄ…tek', 'saturday' : u'sobota', 'sunday' : u'niedziela', } … | |
Re: Iterate on all the list elements except the last one: [code=Python]numblist = [1, 2, 3, 5, 6, 7, 8, 9, 11] for i in range(len(numblist)-1): if numblist[i] == numblist[i + 1] - 1: print 'NO GAP between indexes %d and %d' % (i, i+1) else: print 'GAP between indexes %d … | |
Re: I am guessing that you used 'str' as a variable name. [code]>>> str = 'abc' >>> print str(123.456) Traceback (most recent call last): File "<interactive input>", line 1, in ? TypeError: 'str' object is not callable >>> del str >>> print str(123.456) 123.456 >>> [/code] | |
Re: Here is another way, also using Python's list sort method. [code] data = [ "ABGH SDFDS 123\n", "SDFS sDF 12\n", "DEF SDFDS 124\n", "ABGH SDFDS 2\n", "SDFS sDF 10\n", "DEF SDFDS 100\n", "DEF SDFDS 1\n", "XYZ DXDER 0\n", "SDFS aDF 12\n"] def sort_on_col(a, b): # function to sort three column … | |
Re: Inheritance! Your new class object [I]fruitcake[/I] will inherit the attributes of [I]object[/I]. See this snippet: [url]http://www.daniweb.com/code/snippet354.html[/url] | |
Re: A dictionaries represents a collection of objects indexed by another collection of immutable key values and are unordered. Method update() would be the easiest way to combine dictionaries, but you can also do it with simple iteration. [code=Python]for key in dict2: dict1[key]=dict2[key][/code] | |
Re: [QUOTE=axn;611879]i can write to the file with no issues, but cant read. i have defined the file to append so as not to overwrite data. then i write to it [B]log_file.writelines(lines)[/B] but the reading wont work?? [B]log_file.readlines(lines)[/B] and thought i could just use log_file = open('%s' % os.path.join(logfile_path, file), 'a+r')[/QUOTE]Close … | |
Re: [I]obj.compDmg()[/I], being a method of fighters[0], will automatically be passed the instance object. In effect, the method receives three arguments in your case. Try this: [code=python]cell.health -= fighters[0].compDmg(cell)[/code] | |
Re: Assuming your data actually has commas in the appropriate places, the following code will determine the company with the highest stock price:[code=Python]import csv f = open(your_data.csv) reader = csv.reader(f) # save header items headerList = reader.next() # Create a dictionary with company name and stock prices dataDict = {} for … | |
Re: The worldwide gross per movie may give some indication of productivity. I'm no accountant, but I would think gross-production costs would be a better one. It's impossible to parse the data you posted, because it is plain text without commas. The number of data items do not match the header … | |
Re: Example using the timeit module: [code=Python] def my_function(): return results if __name__ == '__main__': import timeit t = timeit.Timer("my_function()", "from __main__ import my_function") print t.timeit(1000)[/code] Note that [I]timeit()[/I] defaults to 1,000,000 iterations. If your function is somewhat slow, you may want to specify the number of iterations (1000 in the … | |
Re: The csv module is ideal for your parsing your data. [code=Python]import csv fn = 'data.csv' f = open(fn) reader = csv.reader(f) headerList = reader.next() outputList = [] for line in reader: # test for True in case there is a blank line if line: dd = {} for i, key … | |
Re: This works:[code=Python]while True: input = raw_input("Are you ready?") if input: print 'you said something' else: print 'you said nothing' break[/code] |
The End.