104 Posted Topics

Member Avatar for grambo

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 …

Member Avatar for jlm699
0
130
Member Avatar for Bouzy210

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]

Member Avatar for jlm699
0
153
Member Avatar for chg

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]

Member Avatar for crono5788
0
150
Member Avatar for kiddo39

#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]

Member Avatar for kiddo39
0
112
Member Avatar for axn

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]

Member Avatar for axn
0
106
Member Avatar for mece

You must close the file object to flush the output buffers. You can manually flush the buffers with file method [I]flush()[/I].

Member Avatar for mece
0
779
Member Avatar for pyth0n

[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]

Member Avatar for pyth0n
0
5K
Member Avatar for ganil123

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]

Member Avatar for lllllIllIlllI
0
227
Member Avatar for luke77

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'] >>>

Member Avatar for luke77
0
124
Member Avatar for Dart82

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 …

Member Avatar for Dart82
0
110
Member Avatar for vmars

[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 …

Member Avatar for bvdet
0
113
Member Avatar for unkwntech

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]

Member Avatar for bvdet
0
135
Member Avatar for Daiosmith

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 …

Member Avatar for shadwickman
0
110
Member Avatar for paynegm

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 …

Member Avatar for jlm699
0
77
Member Avatar for jworld2

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', …

Member Avatar for jworld2
0
147
Member Avatar for knish

[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 …

Member Avatar for ghostdog74
0
141
Member Avatar for Agni

Use string method [I]strip()[/I] to remove newline characters. [code=Python]for line in lines: filemenu.add_cascade(label=line.strip())[/code]

Member Avatar for Agni
0
242
Member Avatar for iamthwee

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 …

Member Avatar for bvdet
0
396
Member Avatar for Hazey

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 …

Member Avatar for bvdet
0
74
Member Avatar for dineshdileep

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() …

Member Avatar for zachabesh
0
91
Member Avatar for damyt01

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 …

Member Avatar for bvdet
0
96
Member Avatar for g_e_young

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, …

Member Avatar for g_e_young
0
1K
Member Avatar for ndoe

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" …

Member Avatar for ndoe
0
114
Member Avatar for Dekudude

You don't need regex for this: [code]>>> array = ['red','blue'] >>> array1 = [' %s ' % item for item in array] >>> array1 [' red ', ' blue '] >>> [/code]

Member Avatar for Dekudude
0
132
Member Avatar for fmv2011

[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.

Member Avatar for Ene Uran
0
371
Member Avatar for StarryEyedSoy

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 …

Member Avatar for jlm699
0
142
Member Avatar for docaholic

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 …

Member Avatar for docaholic
0
160
Member Avatar for ChrisP_Buffalo

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 …

Member Avatar for bvdet
0
5K
Member Avatar for Mazille

It appears that you omitted an operator: yIntercept = y1 - (((y2 - y1)/(x2 - x1))[B][COLOR="Red"](add operator here)[/COLOR][/B](x1))

Member Avatar for Mazille
0
139
Member Avatar for dinilkarun

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' …

Member Avatar for woooee
0
418
Member Avatar for linip

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]

Member Avatar for bvdet
0
75
Member Avatar for k.wiseman

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]

Member Avatar for k.wiseman
0
123
Member Avatar for dinilkarun
Member Avatar for dinilkarun
0
236
Member Avatar for mengqing

The string method splitlines() can preserve trailing newlines.[code]>>> string.splitlines(1) ['Hello\n', 'World'] >>> [/code]

Member Avatar for bvdet
0
107
Member Avatar for dr_kac

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 …

Member Avatar for paddy3118
0
191
Member Avatar for indu_shreenath

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 …

Member Avatar for bvdet
0
106
Member Avatar for cheechand

>>> s = 'airplane' >>> list(s) ['a', 'i', 'r', 'p', 'l', 'a', 'n', 'e'] >>>

Member Avatar for lllllIllIlllI
0
72
Member Avatar for spoksss

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', } …

Member Avatar for bvdet
0
129
Member Avatar for parmenio79

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 …

Member Avatar for parmenio79
0
27K
Member Avatar for atsuko

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]

Member Avatar for atsuko
0
159
Member Avatar for dr_kac

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 …

Member Avatar for bvdet
0
139
Member Avatar for lllllIllIlllI

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]

Member Avatar for bvdet
0
106
Member Avatar for nuaris

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]

Member Avatar for nuaris
0
749
Member Avatar for axn

[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 …

Member Avatar for bvdet
0
104
Member Avatar for FreezeBlink

[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]

Member Avatar for bvdet
0
192
Member Avatar for ssDimensionss

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 …

Member Avatar for bvdet
0
180
Member Avatar for sch0009

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 …

Member Avatar for bvdet
0
264
Member Avatar for lllllIllIlllI

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 …

Member Avatar for woooee
0
84
Member Avatar for shigehiro

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 …

Member Avatar for a1eio
0
260
Member Avatar for slayr-cxf50

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]

Member Avatar for Lardmeister
0
94

The End.