473,474 Members | 1,673 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Formatting text files

1 New Member
Im starting new project where I have to take data from one text file and toss it into another is a specified format ( i have a 27 page document outlining that format). I am new to python and was wondering if anyone had some tips on usefull ways to parse text files using python?
Jan 5 '07 #1
5 6436
bvdet
2,851 Recognized Expert Moderator Specialist
Im starting new project where I have to take data from one text file and toss it into another is a specified format ( i have a 27 page document outlining that format). I am new to python and was wondering if anyone had some tips on usefull ways to parse text files using python?
I'm no expert on parsing data, but regular expressions (module re) is a powerful tool.
Jan 5 '07 #2
bartonc
6,596 Recognized Expert Expert
Im starting new project where I have to take data from one text file and toss it into another is a specified format ( i have a 27 page document outlining that format). I am new to python and was wondering if anyone had some tips on usefull ways to parse text files using python?
Python has many powerful and easy to use tools for dealing with text. So many, in fact, that picking the tools is sometimes the hard part. After getting a grasp on the language syntax and structures, parsing text is fairly easy to implement.
Jan 6 '07 #3
badech
16 New Member
hello
i hope this is useful
http://ibiblio.org/obp/thinkCS/pytho...ml/chap11.html

you can see also :
http://users.info.unicaen.fr/~fhoube...honcours9B.pdf

http://www.cifen.ulg.ac.be/inforef/s...otes_hyper.pdf
chapter 9 ( page 112 )
but it's in french
Jan 6 '07 #4
dshimer
136 Recognized Expert New Member
In my mind it also depends a great deal on the structure of the text. I do this task constantly and because of the setting I am in I deal primarily with two types of data files.

One is text or numeric data that is fairly structured, for example each line may contain a variety of numbers or strings delimited by a character or white space. For example to describe a point in space, a file may have hundreds of lines with
Name,X,Y,Z,R1,R2,R3,Desc
Where Name is the name of a point, x,y,z, are geographic coordinates and the R's are some kind of real numbers, and Desc is a text description. When working with these kinds of files I find it easiest to take the data from the input file and create a list of lists then just loop over the lists outputing the data in the new format. I usually grab the whole file using readlines() then run it through a function I call lines2lists which works on data separated by whitespace but could easily be modified to add a delimiter variable.

Expand|Select|Wrap|Line Numbers
  1. def lines2lists(AListOfDataLines):
  2.     '''
  3.     Function readlines returns an entire file with each line as a string in a
  4.     list of data.  This function will convert each string into a list of words,
  5.     then return a list of lists.
  6.     Example:            lines2lists(['first line','the second line','or sentences'])
  7.     Would return:       [['first','line'],['the','second','line'],['or','sentences]]
  8.     '''
  9.     DataList=[]
  10.     for Line in AListOfDataLines:
  11.         DataList.append(Line.split())
  12.     return DataList
  13.  
I usually combine it with readlines(), for example
Expand|Select|Wrap|Line Numbers
  1. Data=utilitymodule.lines2lists(AnOpenFile.readlines())
Where Data is the resulting list in which the example above would look something like the following.
[[Name,X,Y,Z,R1,R2,R3,Desc],[Name,X,Y,Z,R1,R2,R3,Desc],[Name,X,Y,Z,R1,R2,R3,Desc]]

The for each element in Data I format and output the elements of each coordinate (in this case).

The other type of file I work with a lot is one in which there may be multiple elements of a particular dataset but they are on different lines of the file. Using the example above it might look like.
Name1 aString
Name2 aString
X1 aNumber
X2 aNumber
Y1 aNumber
Y2 aNumber
and so on....

In this case I still read in the lines, build lists from them, then use something like the count() function to test for a value in a particular list, if the test value exists, I grab the other member of the list which is the actual data then append it to the actual list of data. In pseudocode it would be something like

If InputString.count(test value like name1) is true then datastring.append( the value associated with name1) then when all the input strings have been parsed. for each element of datastring, format and output the values.

There are probably easier ways to do this, but most of the time I may only need to write a program every couple of weeks, may only have 5 minutes notice and need to have it done very quickly. Since there is so much power in lists I tend to stick with the functions I know and love and can hack together quickly.
Jan 9 '07 #5
bvdet
2,851 Recognized Expert Moderator Specialist
dshimer,
Whatever works for you in a efficient manner IS the easiest way. Here are two things that I learned on this forum:
Expand|Select|Wrap|Line Numbers
  1. f = open(dlg1.import_file, "r")
  2. # Files can be used as iterators. Internally, for calls file next() method.
  3. for item in f:
  4.     ....do stuff....
Expand|Select|Wrap|Line Numbers
  1. # If a sub-string is in a string, evaluate True
  2. if "subject_text" in item.lower():
  3.     pt = re.split('[:;,]', item)
Maybe you can use these sometime.
Jan 9 '07 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: Colleyville Alan | last post by:
I am using Access and have embedded the ActiveX control Formula One that came with Office 2000. (ver 3.04). I have created and formatted a spreadsheet and now I want to copy the info with...
4
by: Bradley | last post by:
I have an A2000 database in which I have a continuous form with a tick box. There is also a text box with a conditional format that is based on the expression , if it's true then change the...
8
by: Mike MacSween | last post by:
tblCourses one to many to tblEvents. A course may have an intro workshop (a type of event), a mid course workshop, a final exam. Or any combination. Or something different in the future. At...
8
by: coleenholley | last post by:
I'm trying to format this bit of code into a numeric format of 12,123 no decimals in the particular format. Here's the code: tbl_worksheet1.Rows(b).Cells(2).Text() = Format(ls_sum_gasohol,...
6
by: Brad | last post by:
I guess I still have not grasped the logic of formatting a simple label or text box. Why would the following not work? I need the resulting label to display currency. lblAmtDue.Text =...
2
by: D. Shane Fowlkes | last post by:
The Smart Indenting "feature" is driving me absolutlely crazy in VWD. Problem: VWD in Code View insists on tabbing a lot of my code over to it's own liking and effects mainly my comments in the...
8
by: alamb200 | last post by:
Hi I have set up a SQL database to contain alist FAQ's for our company and then plan to pull this info off using a web page. So far I have entered the data but I am unable to control how it is...
14
by: Scott M. | last post by:
Ok, this is driving me nuts... I am using VS.NET 2003 and trying to take an item out of a row in a loosely-typed dataset and place it in a label as a currency. As it is now, I am getting my...
1
by: aman909 | last post by:
Hello, Im trying to use conditional formatting in a text box on a form. What im trying to do is that conditional formatting changes the colour of the text in the text box. I need the...
6
by: pteare | last post by:
Hello, I am using access 07 and have some VBA code which puts some text into a memo field for me. It gets the text from various columns of a table. Currently it looks like the below: phil -...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.