Python Print Line Number In File

Posted in: admin22/10/17Coments are closed

I need to get the line number of a phrase in a text file. The phrase could be the dog barked I need to open the file, search it for that phrase and print the line. How can I get the file name and line number in python script. Exactly the file information we get from an exception traceback. In this case without raising an exception. Opening a file and reading the content of a file is pretty easy in Python. One easy way to read a text file and parse each line is to use the python statement. X/f/0/6/f06f65f7e66105480750fa77c477271a4b26f64a.png' alt='Python Print Line Number In File' title='Python Print Line Number In File' />A couple of friends out there are valiantly teaching themselves the Python programming language in their free time. Who are they Hack reporters like me, picking up computer skills in a continuing quest to better sift, organize and analyze information. And, in the process, maybe keep our jobs. Php The mbstring package adds UTF8 aware string functions with mb prefixes. We assume that os, re, and sys are always imported. Grammar and Execution. Execute the Python code contained in script, which must be a filesystem path absolute or relative referring to either a Python file, a directory containing. There are acouple great books available free online but its pretty tough to start stringing all the fundamentals into a problem solving script all on your own. So why not write up some simple recipes that attack problems common to our particular tribe One of the ways computer programming can be of great use to a reporter is as a text parser. We all have more documents than we have time. So a common challenge is training your computer to read through a big blob of text and return any hits on terms youre interested in i. If its a one off effort, you can probably get this done quickly using search tools included in common quality text editors ex. Ultraedit,Notepad, Text. Mate. But if youve got a steady stream of files, like a weekly dump of court filings, or a really big bad file, sometimes its preferable to train your computer to do the work for you. In that spirit, the following instructions are designed to show you how to use Python to search through a text file The Sonnets of William Shakespeare, find any lines that contain our sample search term love, and then print out the hits into a new file we can keep as a memento. Well be dealing with a source file thats probably cleaner than most documents youll get from the government, and certainly a lot tidier than anything youve converted from a PDF file using an OCR application, but if youre a totally newbie, my hope is that this can help you get a grip on how the hell all the pieces described in the textbooks fit together into something almost useful. Since Im now a full time geek, I do most of my work on computers that run some flavor of Linux. The step by step instructions that follow will walk you through each keystroke on the command line in Ubuntu, which is what I run at home. But since most people who might be interested in this are probably running Windows XP or Mac OS X, Ill try to include translations as we go. The one prerequsite for the whole endeavor is that you already have a working installation of Python. If youre working in Windows and you dont, Id recommend visiting Active. State and downloading the installer for their Active. Python distribution. If youre rocking a Macbook, you can find out whether youre rolling with Python by opening your terminal and entering the following If youve got it properly installed, it should return something like. If its not working out, Id recommend the installation instructions in Mark Pilgrims excellent book, Dive Into Python. Alright, with all that out of the way, lets get to the recipe. Open the command line, create a working directory, move there. HOME. mkdir Documentspy search. Documentspy search. Wireless Wifi Hacker on this page. The three commands above, which should work just as easily in Mac as in Linux, will move us to our home directory, create a new subdirectory in your Documents folder, and relocate to the new folder. If youre working in Windows, youll be on the C file structure, rather than the Unix style structure above. So you might mkdir a new working directory in your C TEMP folder or wherever else youd like to work. Or just make a folder wherever through Windows Explorer and cd there after the fact through the command line. Download our source file, The Sonnets of William Shakespeare. O http www. gutenberg. The line above uses the curl command line utility to download a copy of Shakespeares work from the Project Gutenberg Web site. Mac users with curl installed should be able to issue the same command. Windows users, or anyone without curl, will probably be able to most easily snatch the file just by visiting the link in a web browser and saving the file to the working directory created in step one. Create our python script in the text editor of your choice. The line above, which again should work for Linux or Mac, will open a new file in vim, the command line text editor that I prefer. You can follow along, or feel free to make your own file in the application you prefer. If youre a newbie Windows user, Notepad should work great. If youre following along in vim, youll need to enter insert mode so you can start entering text. Do that by hitting 4. Write the codeusrbinenv pythonimportreshakesopenwssnt. Llove. ,line printline,If, like my friends, youve been working through some common Python tutorials, Im guessing a lot of that looks familar to you. The first line is a shebang that, on execution of the file, instructs the computer to process the script using the python interpreter. The import re pulls in Pythons standard regular expression module so we can use it later to search the text. The open command grabs the Shakespeare file weve just downloaded and opens it up. The r is for read mode. The three staggered statements that follow are a loop that runs through each line in the document, as dictated by the first statement. The second statement uses the re. So, what is that thing Llove., say whatThats a regular expression I designed specifically to catch any instances of the search term Im after. If youre not familar with regular expressions, theyre a powerful language for matching strings of text. When you first get started, they can be a bit intimidating, but once you learn a couple tricks, youll quickly see how useful they can be. One of my favorite geek jokes is this cartoon on the utility of a well timed regexSo how does it work There are two tricks to learn. Remember, our goal is to find any line in Shakespeares sonnets that include the word love. But, when we think about it, we cant just search for love because our loop is evaluating the text line by line, not word by word. So if we just ask for love, wed only get lines that include only the word love. Plus the word could appear in any number of common grammatical variations ex. Love, lover, lovesick, self love that wed also like to capture. Thats where the regular expressions come in. Youll notice that the expression is bracketed by two. In regular expression language, the. When bracketed around a search term, like love, it should return a match on a line of text regardless of where in the line love appears. In other words, it would match She loves you,love is a many spendored thing or aint talking bout love. But, all by itself. America What Time is Love or Love Is Only A Feeling. Why not Because those songs have an uppercase L and were just asking for lowercase. Bummer, right One way to fix that would be to add an option that gives the regular expression variations on the term to look for. You can do that by adding another parenthesis set and separating the options with a pipe. Thats where the Ll above came from. Combine that with the. Though quick studies will catch a flaw in the design.