Showing posts with label strip. Show all posts
Showing posts with label strip. Show all posts

Friday, October 15, 2010

Python - Anagram generator

# python anagram generator 
# 
# This anagram generator uses a 
# text file as a reference for 
# appropriate words. 
# 
# The word file I used is in the 
# following format (each word has 
# it's own line): 
# 
# act 
# addition 
# adjustment 
# advertisement 
# after 
# again 
# against 
# ... and on and on... 
# 
 
def isAnagramOf(attempt, original):
    # all the same case 
    attempt = attempt.strip()
    if len(attempt) < 1: # only actual words 
        return False
    attempt, original = attempt.lower(), original.lower()
    for character in attempt:
        position = original.find(character)
        if (position == -1):
            return False
        original = original.replace(character, '', 1)
    return True
 
def getAnagramsFor(text):
    anagrams = []
    wordlist = open("wordlist.txt", 'r')
    for line in wordlist:
        line = line.strip("\n") #strip the carriage return 
        if isAnagramOf(line, text):
            anagrams.append(line)
    return anagrams
 
matching_anagrams = getAnagramsFor("pythonic prose")
print(len(matching_anagrams), "total anagrams generated")
for ana in matching_anagrams:
    print(ana)
 
 
# my output: 
# 
# 66 total anagrams generated 
# chest 
# chin 
# copper 
# copy 
# cry 
# he 
# history 
# hope 
# ... skip a few ... 
# theory 
# thin 
# this 
# tin 
# to 
# toe 
# top 
# yes 
 

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 - generate double dutch

# this example is similar 
# to the double dutch generator 
 
def createDoubleDutch(word):
    ''' 
        create and return a double 
        dutch version of word 
    ''' 
    for v in ("a", "e", "i", "o", "u", "y"):
        # double dutch-ize each vowel 
        word = word.replace(v, v+"b"+v)
    return word
 
if __name__ == '__main__':
    ddSentence = "" 
    for w in "My sample sentence for double dutch".split(' '):
           ddSentence += createDoubleDutch(w) + " " 
    print ddSentence.strip()
 
#output: 
# Myby sabamplebe sebentebencebe fobor doboubublebe dubutch 
 
 

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

Thursday, September 17, 2009

Python - string stripping


# string manipulations
# striping characters out of strings

aUrl = "http://www.example.com"

# strip, lstrip, rstrip only remove characters
#   on the either edge (strip), the left edge (lstrip),
#   and the right edge(rstrip)
print aUrl.strip("htp:/w.com")

#outputs:
#   example

print aUrl.lstrip("htp:/")

#outputs:
#   www.example.com

print aUrl.rstrip(".com")

#outputs:
#   http://www.example

# to strip out all occurances
#   of a character use replace()
print aUrl.replace('m', "")

#outputs:
#   http://www.exaple.co

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"