Skip to main content

Posts

Showing posts from October, 2014

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