Showing posts with label split. Show all posts
Showing posts with label split. Show all posts

Friday, October 15, 2010

Python - palindrome detector

# palindrome detector
#
# parse text and print out palindromes
 
 
# make a map to remove punctuation
punc = {" ":'', ",":'',
        ".":'', "!":'',
        "?":'', "'":'',
        '"':'', ':':'',
        '\n':''}
puncMap = str.maketrans(punc)
 
# determines whether given text is a palindrome
def isPalindrome(text):
    # change to all the same case
    text = text.lower()
    # remove punctuation
    text = text.translate(puncMap)
    # to count as a palindrome it must have
    # at least 2 valid characters
    if (len(text) < 2):
        return False
    # palindrome if it reads the same
    # front or backwards
    return text == text[::-1]
 
 
givenText = """
    Hi Mom, welcome. A man, a plan, a canal, panama. And 
    other text. 
    """
 
# first check the whole text
if (isPalindrome(givenText)):
    print("The entire text: '" + givenText.strip() + "' is a palindrome.")
 
# now check by sentence
for sentence in givenText.split('.'):
    if (isPalindrome(sentence)):
        print("The sentence: '" + sentence.strip() + "' is a palindrome.")
 
# now check every word
for word in givenText.split(' '):
    if (isPalindrome(word)):
        print("The word: '" + word.strip() + "' is a palindrome.")
 
# my output:
# The sentence: 'A man, a plan, a canal, panama' is a palindrome.
# The word: 'Mom,' is a palindrome.
 
    
 
 

Tuesday, September 29, 2009

Python - simple regular expression examples

# regular expressions are extremely powerful
# here are some simple examples to get you started

import re

text = "Some example text to manipulate with regular expressions."

# find the location of all the vowels
# iterate through all vowels
# here I've used the finditer method to return and
#   and iterator through the results
for i in re.finditer('[aeiouy]', text):
    print "location:", i.start(), " to ", i.end()
    print "  found text was: ", text[i.start():i.end()]
# output:
#location: 1  to  2
#  found text was:  o
#location: 3  to  4
#  found text was:  e
#
# SNIP -- there are lots of vowels
#
#location: 49  to  50
#  found text was:  e
#location: 52  to  53
#  found text was:  i
#location: 53  to  54
#  found text was:  o

# use regular expressions to split your sentence into words
sentence = "This is my example sentence"
for word in re.split(' ', sentence):
    print word
#Output:
# This
# is
# my
# example
# sentence

# search and replace regular expression functionality
# replace 'regular expression' with 're'
text = "regular expression text goes here"
newText = re.sub('regular expression', 're', text)
print newText
#Outputs:
# re text goes here



Monday, September 28, 2009

Python - pig latin generator

 
 
 
def makePigLatin(word):
    """ convert one word into pig latin """ 
    m  = len(word)
    vowels = "a", "e", "i", "o", "u", "y" 
    # short words are not converted 
    if m<3 or word=="the":
        return word
    else:
        for i in vowels:
            if word.find(i) < m and word.find(i) != -1:
                m = word.find(i)
        if m==0:
            return word+"way" 
        else:
            return word[m:]+word[:m]+"ay" 
 
 
sentence = "Hooray for pig latin" 
pigLatinSentence = "" 
# iterate through words in sentence 
for w in sentence.split(' '):
    pigLatinSentence += makePigLatin(w) + " " 
 
print pigLatinSentence.strip()
 
# output: 
# oorayHay orfay igpay atinlay 
 
 

python - split paragraph into sentences with regular expressions

# split up a paragraph into sentences
# using regular expressions


def splitParagraphIntoSentences(paragraph):
    ''' break a paragraph into sentences
        and return a list '''
    import re
    # to split by multile characters

    #   regular expressions are easiest (and fastest)
    sentenceEnders = re.compile('[.!?]')
    sentenceList = sentenceEnders.split(paragraph)
    return sentenceList


if __name__ == '__main__':
    p = """This is a sentence.  This is an excited sentence! And do you think this is a question?"""

    sentences = splitParagraphIntoSentences(p)
    for s in sentences:
        print s.strip()

#output:
#   This is a sentence
#   This is an excited sentence

#   And do you think this is a question

Tuesday, September 15, 2009

Python - reorder a sentence alphabetically

# reorder the words in a sentence alphabetically


def sentenceAlphabetizer(sentence):
    words = sentence.split(' ')
    words.sort()
    sentence = ""
    for word in words:
        sentence += word + " "
    return sentence.strip()



if __name__ == '__main__':
    print sentenceAlphabetizer("basic applepie zoo party")

#output:
#   'applepie basic party zoo'

Friday, September 4, 2009

Python reverse word order of a sentence

# reverse the order of words in a sentence (python 2.6.1)
#   you may also be interested 
#  in alphabetizing the words in a sentence 

def reverseWordOrderOfSentence(sentence):


    #break the sentence into words with split()
    words = sentence.split(' ')


    #reverse the order of the words list
    #in python 2.6.1 a list.reverse() is done to the calling list object

    # older versions return a reversed list..... so
    # words = words.reverse()
    words.reverse()


    #iterate through and build the new sentence
    newSentence = ""

    for word in words:
        newSentence += " " + word


    #return and strip out beginning or trailing white space

    return newSentence.strip()


if __name__ == '__main__':
    print reverseWordOrderOfSentence("Hooray for Pythonic Prose")

#input sentence:
# # "Hooray for Pythonic Prose"

#
#output:
# "Prose Pythonic for Hooray"