Программка на Питоне - для тех, кто хочет посмотреть на его красивый синтаксис:
WordCount - подсчитать слова в тексте
# Import the string module, so we can call Python's standard
# string-related functions.
import string
def CountWords(Text):
"Count how many times each word occurs in Text."
# A string immediately after a def statement is a
# "docstring" - a comment intended for documentation.
WordCount={}
# We will build up (and return) a dictionary whose keys
# are the words, and whose values are the corresponding
# number of occurrences.
CurrentWord=""
# To make the job cleaner, add a period at the end of the
# text; that way, we are guaranteed to be finished with
# the current word when we run out of letters:
Text=Text+"."
# We assume that ' and - don't break words, but any other
# nonalphabetic character does. This assumption isn't
# entirely accurate, but it's close enough for us.
# string.letters is a string of all alphabetic characters.
PiecesOfWords = string.letters + "'-"
# Iterate over each character in the text. The
# function len() returns the length of a sequence,
# such as a string:
for CharacterIndex in range(0,len(Text)):
CurrentCharacter=Text[CharacterIndex]
# The find() method of a string finds
# the starting index of the first occurrence of a
# substring within a string, or returns -1
# if it doesn't find the substring. The next
# line of code tests to see whether CurrentCharacter
# is part of a word:
if (PiecesOfWords.find(CurrentCharacter)!=-1):
# Append this letter to the current word.
CurrentWord=CurrentWord+CurrentCharacter
else:
# This character is not a letter.
if (CurrentWord!=""):
# We just finished off a word.
# Convert to lowercase, so "The" and "the"
# fall in the same bucket.
CurrentWord = string.lower(CurrentWord)
# Now increment this word's count.
CurrentCount=WordCount.get(CurrentWord,0)
WordCount[CurrentWord]=CurrentCount+1
# Start a new word.
CurrentWord=""
return (WordCount)
if (__name__=="__main__"):
# Read the text from the file song.txt.
TextFile=open("song.txt","r")
Text=TextFile.read()
TextFile.close()
# Count the words in the text.
WordCount=CountWords(Text)
# Alphabetize the word list, and print them all out.
SortedWords=WordCount.keys()
SortedWords.sort()
for Word in SortedWords:
print Word,WordCount[Word]
результат вроде этого:
sortedwords 3
standard 1
start 1
starting 1
statement 1
string 10
string-related 1
substring 2
such 1
tests 1
text 12
Добавлено
CGIDebug
import sys
import traceback
sys.stderr = sys.stdout
print "Content-Type: text/html\n"
try:
# The script body goes here!
except:
print "\n\n<PRE>"
traceback.print_exc()
Feedback
#!python
import cgi
import smtplib
import sys
import traceback
# Set these e-mail addresses appropriately
SOURCE_ADDRESS="robot_form@gianth.com"
FEEDBACK_ADDRESS="dumplechan@seanbaby.com"
sys.stderr = sys.stdout
print "Content-Type: text/html\n"
try:
fields=cgi.FieldStorage()
if (fields.has_key("name") and fields.has_key("comments")):
UserName=fields["name"].value
Comments=fields["comments"].value
# Mail the feedback:
Mailbox=smtplib.SMTP("mail.seanbaby.com")
MessageText="From: <"+SOURCE_ADDRESS+">\r\n"
MessageText+="To: "+FEEDBACK_ADDRESS+"\r\n"
MessageText+="Subject: Feedback\r\n\r\n"
MessageText+="Feedback from "+UserName+":\r\n"+Comments
Mailbox.sendmail(SOURCE_ADDRESS, FEEDBACK_ADDRESS,
MessageText)
# Print a simple thank-you page:
print "<h1>Thanks!</h1>Thank you for your feedback!"
else:
# They must have left "name" and/or "comments" blank:
print "<h1>Sorry...</h1>"
print "You must provide a name and some comments too!"
except:
# Print the traceback to the response page, for debugging!
print "\n\n<PRE>"
traceback.print_exc()
HelloWorld
# (add #! line here under UNIX, or if using Apache on Windows)
import cgi
# Part 1: Content-Type header, followed by a blank line
# to indicate the end of the headers.
print "Content-Type: text/html\n"
# Part 2: A simple HTML page
print "<title>Gumby</title>"
print "<html><body>My brain hurts!</body></html>
NewsSlurp
import nntplib
import sys
def dump_articles(news,TargetGroup,TargetPoster):
GroupInfo=news.group(TargetGroup)
ArticleList=news.xhdr("from",GroupInfo[2]+"-"+GroupInfo[3])
dumpfile = open("newsfeed.txt","w")
for ArticleTuple in ArticleList:
(MessageID,Poster)=ArticleTuple
if (Poster.find(TargetPoster)!=-1):
ArticleText=news.body(MessageID)[3]
for ArticleLine in ArticleText:
dumpfile.write(ArticleLine+"\n")
dumpfile.flush()
dumpfile.close()
news=nntplib.NNTP("news.fastpointcom.com")
dump_articles(news,"alt.religion.kibology","kibo@world.std.com")
popmail
import poplib
# Replace server, user, and password with your
# mail server, user name, and password!
Mailbox=poplib.POP3("mail.seanbaby.com")
Mailbox.user("dumplechan@seanbaby.com")
Mailbox.pass_("secretpassword")
MyMessage=Mailbox.retr(1)
FullText="" # Build up the message body in FullText
PastHeaders=0
for MessageLine in MyMessage[1]:
if PastHeaders==0:
# A blank line marks the end of headers:
if (len(MessageLine)==0):
PastHeaders=1
else:
FullText+=MessageLine+"\n"
Mailbox.quit()
print FullText
WebSearch
import httplib
import htmllib
import urllib
import formatter
# Encode our search terms as a URL, by
# passing a dictionary to urlencode
SearchDict={"q":"Charles Dikkins",
"kl":"XX","pg":"q","Translate":"on"}
SearchString=urllib.urlencode(SearchDict)
print "search:",SearchString
Request=httplib.HTTP("www.altavista.com")
Request.putrequest("POST","/cgi-bin/query")
Request.putheader(?€?Accept?€™, ?€?text/plain?€™)
Request.putheader(?€?Accept?€™, ?€?text/html?€™)
Request.putheader(?€?Host?€™, ?€?www.alta-vista.com?€™)
Request.putheader("Content-length",`len(SearchString)`)
Request.endheaders()
Request.send(SearchString)
print Request.getreply()
# Read and parse the resulting HTML
HTML=Request.getfile().read()
MyParser=htmllib.HTMLParser(formatter.NullFormatter())
MyParser.feed(HTML)
# Print all the anchors from the results page
print MyParser.anchorlist
все эти примерчики стырены отсюда: http://www.pythonapocrypha.com
Добавлено
точнее
http://www.pythonapocrypha.com/PySource.zip
WordCount - подсчитать слова в тексте
# Import the string module, so we can call Python's standard
# string-related functions.
import string
def CountWords(Text):
"Count how many times each word occurs in Text."
# A string immediately after a def statement is a
# "docstring" - a comment intended for documentation.
WordCount={}
# We will build up (and return) a dictionary whose keys
# are the words, and whose values are the corresponding
# number of occurrences.
CurrentWord=""
# To make the job cleaner, add a period at the end of the
# text; that way, we are guaranteed to be finished with
# the current word when we run out of letters:
Text=Text+"."
# We assume that ' and - don't break words, but any other
# nonalphabetic character does. This assumption isn't
# entirely accurate, but it's close enough for us.
# string.letters is a string of all alphabetic characters.
PiecesOfWords = string.letters + "'-"
# Iterate over each character in the text. The
# function len() returns the length of a sequence,
# such as a string:
for CharacterIndex in range(0,len(Text)):
CurrentCharacter=Text[CharacterIndex]
# The find() method of a string finds
# the starting index of the first occurrence of a
# substring within a string, or returns -1
# if it doesn't find the substring. The next
# line of code tests to see whether CurrentCharacter
# is part of a word:
if (PiecesOfWords.find(CurrentCharacter)!=-1):
# Append this letter to the current word.
CurrentWord=CurrentWord+CurrentCharacter
else:
# This character is not a letter.
if (CurrentWord!=""):
# We just finished off a word.
# Convert to lowercase, so "The" and "the"
# fall in the same bucket.
CurrentWord = string.lower(CurrentWord)
# Now increment this word's count.
CurrentCount=WordCount.get(CurrentWord,0)
WordCount[CurrentWord]=CurrentCount+1
# Start a new word.
CurrentWord=""
return (WordCount)
if (__name__=="__main__"):
# Read the text from the file song.txt.
TextFile=open("song.txt","r")
Text=TextFile.read()
TextFile.close()
# Count the words in the text.
WordCount=CountWords(Text)
# Alphabetize the word list, and print them all out.
SortedWords=WordCount.keys()
SortedWords.sort()
for Word in SortedWords:
print Word,WordCount[Word]
результат вроде этого:
sortedwords 3
standard 1
start 1
starting 1
statement 1
string 10
string-related 1
substring 2
such 1
tests 1
text 12
Добавлено
CGIDebug
import sys
import traceback
sys.stderr = sys.stdout
print "Content-Type: text/html\n"
try:
# The script body goes here!
except:
print "\n\n<PRE>"
traceback.print_exc()
Feedback
#!python
import cgi
import smtplib
import sys
import traceback
# Set these e-mail addresses appropriately
SOURCE_ADDRESS="robot_form@gianth.com"
FEEDBACK_ADDRESS="dumplechan@seanbaby.com"
sys.stderr = sys.stdout
print "Content-Type: text/html\n"
try:
fields=cgi.FieldStorage()
if (fields.has_key("name") and fields.has_key("comments")):
UserName=fields["name"].value
Comments=fields["comments"].value
# Mail the feedback:
Mailbox=smtplib.SMTP("mail.seanbaby.com")
MessageText="From: <"+SOURCE_ADDRESS+">\r\n"
MessageText+="To: "+FEEDBACK_ADDRESS+"\r\n"
MessageText+="Subject: Feedback\r\n\r\n"
MessageText+="Feedback from "+UserName+":\r\n"+Comments
Mailbox.sendmail(SOURCE_ADDRESS, FEEDBACK_ADDRESS,
MessageText)
# Print a simple thank-you page:
print "<h1>Thanks!</h1>Thank you for your feedback!"
else:
# They must have left "name" and/or "comments" blank:
print "<h1>Sorry...</h1>"
print "You must provide a name and some comments too!"
except:
# Print the traceback to the response page, for debugging!
print "\n\n<PRE>"
traceback.print_exc()
HelloWorld
# (add #! line here under UNIX, or if using Apache on Windows)
import cgi
# Part 1: Content-Type header, followed by a blank line
# to indicate the end of the headers.
print "Content-Type: text/html\n"
# Part 2: A simple HTML page
print "<title>Gumby</title>"
print "<html><body>My brain hurts!</body></html>
NewsSlurp
import nntplib
import sys
def dump_articles(news,TargetGroup,TargetPoster):
GroupInfo=news.group(TargetGroup)
ArticleList=news.xhdr("from",GroupInfo[2]+"-"+GroupInfo[3])
dumpfile = open("newsfeed.txt","w")
for ArticleTuple in ArticleList:
(MessageID,Poster)=ArticleTuple
if (Poster.find(TargetPoster)!=-1):
ArticleText=news.body(MessageID)[3]
for ArticleLine in ArticleText:
dumpfile.write(ArticleLine+"\n")
dumpfile.flush()
dumpfile.close()
news=nntplib.NNTP("news.fastpointcom.com")
dump_articles(news,"alt.religion.kibology","kibo@world.std.com")
popmail
import poplib
# Replace server, user, and password with your
# mail server, user name, and password!
Mailbox=poplib.POP3("mail.seanbaby.com")
Mailbox.user("dumplechan@seanbaby.com")
Mailbox.pass_("secretpassword")
MyMessage=Mailbox.retr(1)
FullText="" # Build up the message body in FullText
PastHeaders=0
for MessageLine in MyMessage[1]:
if PastHeaders==0:
# A blank line marks the end of headers:
if (len(MessageLine)==0):
PastHeaders=1
else:
FullText+=MessageLine+"\n"
Mailbox.quit()
print FullText
WebSearch
import httplib
import htmllib
import urllib
import formatter
# Encode our search terms as a URL, by
# passing a dictionary to urlencode
SearchDict={"q":"Charles Dikkins",
"kl":"XX","pg":"q","Translate":"on"}
SearchString=urllib.urlencode(SearchDict)
print "search:",SearchString
Request=httplib.HTTP("www.altavista.com")
Request.putrequest("POST","/cgi-bin/query")
Request.putheader(?€?Accept?€™, ?€?text/plain?€™)
Request.putheader(?€?Accept?€™, ?€?text/html?€™)
Request.putheader(?€?Host?€™, ?€?www.alta-vista.com?€™)
Request.putheader("Content-length",`len(SearchString)`)
Request.endheaders()
Request.send(SearchString)
print Request.getreply()
# Read and parse the resulting HTML
HTML=Request.getfile().read()
MyParser=htmllib.HTMLParser(formatter.NullFormatter())
MyParser.feed(HTML)
# Print all the anchors from the results page
print MyParser.anchorlist
все эти примерчики стырены отсюда: http://www.pythonapocrypha.com
Добавлено
точнее
http://www.pythonapocrypha.com/PySource.zip