tags:

views:

72

answers:

1

I am trying to make a disorganized text file into a list suitable for use with another python program. The text file is a list of data seperated by a few spaces but not in standard columns or anything organized. The goal of this program is to read through the file using python and after each piece of data that I want there is a space, so I want to make a new line. The output should be a list of data with each term on one line. In addition there are some terms that I do not want. All the terms that I want start with "JJ".

Here is what i have so far. Note this does not run yet. I am looking for help finishing this program that will select all the terms starting with JJ and make a new line at the space after the JJ term. Thanks Robert

datafile = open ('C:\\textfile.txt', 'r')

line_list = line.split(" ")
for x in line_list:
    if x.startswith("JJ") : print line_list

EDIT: So i want to open the file called textfile and have python keep only the lines of data that start with "JJ". Additionaly I want each data to be on it's own line, which is why I want to seperate them using the space after each ilne of data? Is that clearer?

A: 

lines = [item for item in open('C:\textfile.txt', 'r').read().split(' ') if item.startswith("JJ")]

Blue Peppers
Is that the only line of code I need then?
Robert A. Fettikowski
That will return a list of every item, separated by spaces, in the file with JJ at the front.
Blue Peppers
@Blue Peppers: I think the example would look better spread over more than one line. One-liners are cute but not always easy to understand or maintain, especially in a teaching context.
Bryan Oakley
Bryan, the loop version of this actually looks rather ugly (at least to me). With your reputation, you could always edit Peppers' post to include the multi-line version.
Wayne Werner