Skip to main content

Posts

Showing posts with the label Python

Tutorial: Look for strings that start with a specific sub-string using regular expression in Python

In this example, we used regular expression to implement the strings.startswith() function. The program will ask for users' input on a sub-string to find at the beginning of each string. The program will then open a file and print out the lines that start with the sub-string being specified. #Implementing Python's string.startswith() using regular expression # import the regular expression module import re # allow users to specify what string to look for as the start of a string start_str = raw_input("Enter the string that starts a line: ") # specify the name of the file to search within file_name = 'my_file.txt' # open the file for reading file_h = open(file_name, 'r') # define the pattern # ^ : start of the string # {} : place holder for start_str # ^{} -> ^start_str # -> pattern: a string that starts with the content stored in start_str # if You want to specify a word, followed by a space, that starts a string # leave a space after ...

A way to sort a Python dictionary by value, instead of key

Here I used the code on page 122 ~ 123 of the book ' Python for Informatics ’ by Charles Severance (Dr. Chuck) as an example to explain how to sort the key value pairs in a Python dictionary by value. # open the file named remeo.txt fhand = open('romeo.txt') # create a dictionary counts = dict() # read the file line by line for line in fhand: # split the line by whitespace characters (space, tab, newline, return, formfeed) words = line.split() # read the individual word for word in words: # increase the word count by 1 for that specific 'word' counts[word] = counts.get(word, 0 ) + 1 # create our list lst = list() # iterate over each tuple (key value pair) in the list generated by counts.items() for key, val in counts.items(): # create a new tuple (value, key) and append to our list, so that sort() will sort the list by the first element, value. # if we want to sort the list (or you can say dictionary) by key, we ...

Tutorial: Using String.find() and String slicing with [n:m] notation to extract data in Python

When you need to extract data from a string in Python, you can use the built-in String.find() method in Python and the String[n:m] notation to extract the sub-string. string.find(str) will return the starting position of the first instance of str in string. For example. 'abcdecd'.find('cd') will return 2, because the first 'cd' instance starts at position 2 (not 3, since position starts with 0). If no str can be found in the string, the method will return -1. str[n:m] notation will extract the sub-string starting at position n and ending at position m-1, not including the m-th character. For example, if the content of my_str is 'I don't know', my_str[2:] will return 'don't know'. By using string.find() and [n:m] notation, we can write a script to automatically extract the data we need from a string. For example, we have a file test_score.txt that records the scores of all the students enrolled in a class. We know that each line re...

How to install PyQT , QT and SIP on Mac

Step 1: Install QT Download and install from here:  http://qt-project.org/downloads   (Locate where the "qmake" is. For example, "/Applications/Qt5.1.1/5.1.1/clang_64/bin/qmake" when I choose to install qt at "/Applicaitons/Qt5.1.1") Step 2: Install SIP Download the package from here:  http://www.riverbankcomputing.co.uk/software/pyqt/ Unzip it and "cd" into the resulted folder. python configure.py make sudo make install (Review the output messages and locate where sip is installed. For example, "/System/Library/Frameworks/Python.framework/Versions/2.7/bin/sip".) Step 3: Install PyQT Download the package from here:   http://www.riverbankcomputing.co.uk/software/pyqt/ Unzip it and "cd" into the resulted folder. python configure.py --qmake where_qmake_is --sip where_sip_is (ex. python  configure.py  --qmake /Applications/Qt5.1.1/5.1.1/clang_64/bin/qmake --sip /System/Library/Frameworks/Python.fra...

Setup xampp for mod_python

1. install flex (parser): sudo apt-get install flex 2. install xampp developer package 3. sudo  ./configure --with-apxs=/opt/lampp/bin/apxs if you get  "apxs:Error: Command failed with rc=65536..." => download the package: https://svn.apache.org/repos/asf/quetzalcoatl/mod_python/trunk 4. After "sudo make", "sudo make install" in http.conf, add following lines: LoadModule python_module modules/mod_python.so <Directory /some/directory/htdocs/test>     AddHandler mod_python .py     PythonHandler mptest     PythonDebug On </Directory> 5. Write test python script "mptest.py": from mod_python import apache def handler(req):     req.content_type = 'text/plain'     req.write("Hello World!")     return apache.OK

Get attribute name and value of XML using minidom module in Python

#! /usr/bin/python # -*- coding: utf-8 -*- import xml.dom.minidom # your xml string xmlContent = "..." # dom parser dom = xml.dom.minidom.parseString(xmlContent) # get element with tag "photo"        photoList = dom.getElementsByTagName("photo") # get attribute id's value of each 'photo' element        for photo in photoList:     print photo.attributes['id'].value

Install python-mysqldb with lampp on Ubuntu

I try to download python-mysqldb from " http://sourceforge.net/projects/mysql-python/" and run the build/install command: python setup.py build I receive this message: EnvironmentError: mysql_config not found I set mysql_config to "/opt/lampp/bin/mysql_config" (I use lampp) and encounter this error message: cc1: error: unrecognized command line option "-mpentiumpro" cc1: warning: command line option "-felide-constructors" is valid for C++/ObjC++ but not for C cc1: warning: command line option "-fno-rtti" is valid for C++/ObjC++ but not for C error: command 'gcc' failed with exit status 1 so I type sudo apt-get install python-mysqldb and find that I can finally import MySQLdb in python

Some Notes about Installing ConceptNet API & Divinsi on Windows

If you got this error: ValueError: numpy.dtype does not appear to be the correct type object, try to installing Numpy 1.3. After you install Divisi (ex. on Windows), copy the content under C:\Python25\Lib\site-packages\conceptnet-4.0rc2-py2.5.egg  to  C:\Python25\Lib\site-packages\csc. Otherwise, you might get error message like “module csc does not exist.”

Using global variable in Python

1: # two global variable 2: myMin = 360.0 3: myMax = 0.0 4: 5: def MyStatistics( fileName ) : 6: myFile = open (fileName) 7: strList = myFile.readlines() 8: 9: # Specify that these two are global variable 10: global myMin 11: global myMax 12: 13: for str in strList : 14: myFloat = float(str) 15: if ( myFloat > myMax ): 16: myMax = myFloat 17: 18: if ( myFloat < myMin ): 19: myMin = myFloat 20: 21: # a file with number seperate '\n' 22: MyStatistics(FileWithFloat) 23: 24: print 'myMin = %s' % (myMin) 25: print 'myMax = %s' % (myMax)