Posts

Showing posts from July, 2009

Find countries in a file's text using regular expressions and Perl

If you have a file with multiple rows of columns such as: RowID, year, address, journalist separated by tabs, how would you create a report of the rowID, year , country the article was written in? #!/usr/bin/perl use Uniq; $file = "The_text_file_with_addresses.txt"; $filename = $file ; $filename =~ s/\.txt// ; open OUTFILE, "+>$filename.out.txt" or die $!; open INFILE, $file or die $!; print "running...\n" ; close(OUTFILE); $docs = 0 ; while (<INFILE>) { my @agents ; $currentline = $_ ; chomp $currentline ; ( $row_id , $year, $address, $journ) = split(/\t/,$currentline ); if ($address =~ /(Afghanistan|Akrotiri|Albania|Algeria|American Samoa|Andorra|Angola|Anguilla|Antarctica|Antigua and Barbuda|Argentina|Armenia|Aruba|Ashmore and Cartier Islands|Australia|Austria|Azerbaijan|Bahamas, The|Bahrain|Bangladesh|Barbados|Bassas da India|Belarus|Belgium|Belize|Benin|Bermuda|Bhutan|Bolivia|Bosnia and Herzegovina|Botswana|Bouvet Islan...

Check the xml files for valid content

Check that the xml files in a directory are well formed and valid. #!/usr/bin/perl # J C # ------------------------------------------------------------------------- # 10/8/2008 - XML parser to check validity of documents # OUTPUT : errors.txt a file containing the error messages for each file that failed to parse. # Each file that failed to validate has the extension "_invalid.xml" so that it can be manually chacked for bad tokens or missing tags. #-------------------------------------------------------------------------- use XML::Checker::Parser; opendir(DIR, "."); @files = readdir(DIR) or die $!; closedir(DIR); print "checking\n" ; open OUTFILE, ">>errors.txt" or die $!; foreach $filename (@files) { if (($ext) = $filename =~ m/\.(xml|XML)$/) { $filename =~ m/(.+)\.\w{3}/; my $xp = new XML::Checker::Parser ( Handlers => { } ); eval { $xp->parsefile($filename); }; if ($@) { print "$xml_file $filename fai...

Finding the names of blogs on hypemachine that might feature bands you like.

Image
If you have always wanted to web scrape - here is the example for you, this is based on one of the Perl gods's modules: Andy Lester's WWW::MECHANIZE. I use this module for a lot of web parsing and text mining - everything from blogs, to fashion pictures to ophthalmologists. #!/usr/bin/perl use strict ; use WWW::Mechanize; open(TEXT,"+>hypemachine.txt"); open(TEXTe,"+>hypemachine-electrolinks.txt"); print TEXTe "All the blogs on hypemachine\n\n" ; my $mech = WWW::Mechanize->new(); # make an array of browsers to trick google with $mech->agent_alias( 'Windows IE 6' ); #------------------------------ # Manage cookies my $response = $mech->get( "http://hypem.com/list" ); my @linksfound = $mech->find_all_links( url_regex => qr/http:\/\// ); print "response gotten\n" ; foreach (@linksfound) { my $fs = $_->url(), "\n"; print "got $fs\n" ; #...

Get the data from clinical trial xml

This script will fetch the xml from clinicaltrials.gov for trials listed in a column. such as NCT00489671 NCT00084357 NCT00637364 NCT00305760 Sub Clinical_trial_data() ' ' Converts each text hyperlink selected into a working hyperlink On Error Resume Next ActiveWorkbook.Application.ScreenUpdating = False Dim XMLDOC As New MSXML2.DOMDocument60 Dim xnodesls As IXMLDOMNodeList Dim xnode As IXMLDOMNode Dim addr As String Dim Text As String Dim xstring As String Dim xstringPhase As String Dim xstringSponsor As String Dim xstringCondition As String Dim xstringIntervention As String Dim xstringInvestigator As String Dim xstringTitle As String Dim xstringStatus As String Dim xstringStartDate As String Dim xstringEndDate As String Dim xstringEnrollment As String Dim xstringMinAge As String Dim xstringMaxAge As String Dim xCell As Range For Each xCell In Selection If ...

Highlight the cells that DO Not match a regular expression in Excel.

Sub FlagCellsRegeXnoteq() ' ' Converts each text hyperlink selected into a working hyperlink ' Dim strSearch As String Application.ScreenUpdating = False strSearch = InputBox(Prompt:="Search String.", _ title:="Search") If strSearch = vbNullString Then Exit Sub Else Dim re As New RegExp re.Pattern = strSearch Dim xCell As Range For Each xCell In Selection If re.Test(xCell.Text) <> True Then xCell.Select With Selection.Interior .Pattern = xlSolid .PatternColorIndex = xlAutomatic .Color = 65115 .TintAndShade = 0 .PatternTintAndShade = 0 End With End If Next xCell End If MsgBox "Done" ' ' End Sub

Highlight all the cells containing a specific regex in Excel

Sub Flag_Cells_by_RegeXeq() ' ' Converts each text hyperlink selected into a working hyperlink ' Dim strSearch As String Application.ScreenUpdating = False strSearch = InputBox(Prompt:="Search String.", _ title:="Search") If strSearch = vbNullString Then Exit Sub Else Dim re As New RegExp re.Pattern = strSearch re.IgnoreCase = True Dim xCell As Range For Each xCell In Selection If re.Test(xCell.Text) = True Then xCell.Select With Selection.Interior .Pattern = xlSolid .PatternColorIndex = xlAutomatic .Color = vbYellow .TintAndShade = 0 .PatternTintAndShade = 0 End With End If Next xCell End If MsgBox "Done" ' ' End Sub

Transforming xml documents to HTML from XML using XSL and XSLT in Python.

Transforming xml documents to HTML from XML using XSL and XSLT in Python. ''' A script to generate an html file from xml and xsl using xslt ''' import Pyana import os dir = os.getcwd() logtxt = open( "xml-html.log.txt" , "w") def transformit( file ): f = open ( file + "_processed.html", "w") f.write( Pyana.transform2String(source=Pyana.URI( file + ".xml" ), style=Pyana.URI('pubmed_xslt.xsl'))) f.close() def logwr ( string ): logtxt.writelines( string ), #============================================ count = 0 for item in os.listdir(dir): if item.endswith('.xml'): ( fname , ext ) = os.path.splitext( item ) print fname logwr ( "transforming " + fname ) print ( "transforming " + fname ) transformit( fname ) count = count + 1 logwr( "the number of documents is " + str(count) )...

Python Script to Download Apache Logs from a directory on a remote site.

""" This script is used to get a apache log directory and download each file from a list of links """ import urllib from sgmllib import SGMLParser class URLLister(SGMLParser): def reset(self): SGMLParser.reset(self) self.urls = [] def start_a(self, attrs): href = [v for k, v in attrs if k=='href'] if href: self.urls.extend(href) def getTheFile(n): f = urllib.urlopen("http://www.mywebserver.com/logs/" + n) fnew = open ( n , 'w') print ( "getting file: " + n) fnew.write ( f.read() ) fnew.close() usock = urllib.urlopen ("http://www.mywebserver.com/logs/") parser = URLLister() parser.feed(usock.read()) usock.close() parser.close() for url in parser.urls: if (url.find(".log") != -1): print url s= url getTheFile(url)

Simple Email Program in Python

This email program will send email to through the local SMTP server on your localhost. import smtplib mymail = "name@email.com" def mail(serverURL=None, sender='', to='', subject='', text=''): """ Usage: mail('somemailserver.com', 'me@example.com', 'someone@example.com', 'test', 'This is a test') """ headers = "From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n" % (sender, to, subject) message = headers + text mailServer = smtplib.SMTP(serverURL) mailServer.sendmail(sender, to, message) mailServer.quit() mail("127.0.0.1", "haveaniceflight@seeul8tr.com" , mymail,"Have a nice trip", "Try to have a nice time in New Orleans! Get us some great data.")

Download all the files linked on a webpage (linux from scratch)

I want to download all the files from this site: linux from scratch packages I get the index.html file. it's easy now to get all the packages... [jcooper@yakushima ~]$ sed 's/<[^>]*>//g' index.html | awk '{print "http://ftp.lfs-matrix.net/pub/lfs/lfs-packages/6.4/"$1}' | xargs wget thanks to this site for the killer sed script.