473,405 Members | 2,160 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,405 software developers and data experts.

generic text read function

Hi,
matlab has a useful function called "textread" which I am trying to
reproduce
in python.

two inputs: filename, format (%s for string, %d for integers, etc and
arbitary delimiters)

variable number of outputs (to correspond to the format given as
input);

So suppose your file looked like this
str1 5 2.12
str1 3 0.11
etc with tab delimited columns.
then you would call it as

c1,c2,c3=textread(filename, '%s\t%d\t%f')

Unfortunately I do not know how to read a line from a file
using the line format given as above. Any help would be much
appreciated
les

Jul 18 '05 #1
2 4107
>>>>> "les" == les ander <le*******@yahoo.com> writes:

les> Hi, matlab has a useful function called "textread" which I am
les> trying to reproduce in python.

les> two inputs: filename, format (%s for string, %d for integers,
les> etc and arbitary delimiters)

les> variable number of outputs (to correspond to the format given
les> as input);

les> So suppose your file looked like this str1 5 2.12 str1 3 0.11
les> etc with tab delimited columns. then you would call it as

les> c1,c2,c3=textread(filename, '%s\t%d\t%f')

les> Unfortunately I do not know how to read a line from a file
les> using the line format given as above. Any help would be much
les> appreciated les

Not an answer to your question, but I use a different approach to
solve this problem. Here is a simple example

converters = (str, int, float)
results = []
for line in file(filename):
line = line.strip()
if not len(line): continue # skip blank lines
values = line.split('\t')
if len(values) != len(converters):
raise ValueError('Illegal line')
results.append([func(val) for func, val in zip(converters, values)])

c1, c2, c3 = zip(*results)

If you really need to emulate the matlab command, perhaps this example
will give you an idea about how to get started. Eg, set up a dict
mapping format strings to converter functions

d = {'%s' : str,
'%d' : int,
'%f' : float,
}

and then parse the format string to set up your converters and split function.

If you succeed in implementing this function, please consider sending
it to me as a contribution to matplotlib -- http://matplotlib.sf.net

Cheers,
JDH
Jul 18 '05 #2
John Hunter wrote:
>>"les" == les ander <le*******@yahoo.com> writes:

les> Hi, matlab has a useful function called "textread" which I am
les> trying to reproduce in python.

les> two inputs: filename, format (%s for string, %d for integers,
les> etc and arbitary delimiters)

Builing on John's solution, this is still not quite what you're looking for (the
delimiter preference is set for the whole line as a separate argument), but it's
one step closer, and may give you some ideas:

import re

dispatcher = {'%s' : str,
'%d' : int,
'%f' : float,
}
parser = re.compile("|".join(dispatcher))

def textread(iterable, formats, delimiter = None):

# Splits on any combination of one or more chars in delimeter
# or whitespace by default
splitter = re.compile("[%s]+" % (delimiter or r"\s"))

# Parse the format string into a list of converters
# Note that white space in the format string is ignored
# unlike the spec which calls for significant delimiters
try:
converters = [dispatcher[format] for format in parser.findall(formats)]
except KeyError, err:
raise KeyError, "Unrecogized format: %s" % err

format_length = len(converters)

iterator = iter(iterable)

# Use any line-based iterable - like file
for line in iterator:
cols = re.split(splitter, line)
if len(cols) != format_length:
raise ValueError, "Illegal line: %s" % cols
yield [func(val) for func, val in zip(converters, cols)]

# Example Usage:

source1 = """Item 5 8.0
Item2 6 9.0"""

source2 = """Item 1 \t42
Item 2\t43"""
for i in textread(source1.splitlines(),"%s %d %f"): print i ...
['Item', 5, 8.0]
['Item2', 6, 9.0] for i in textread(source2.splitlines(),"%s %f", "\t"): print i ...
['Item 1 ', 42.0]
['Item 2', 43.0] for item, value in textread(source2.splitlines(),"%s %f", "\t"): print item, value
...
Item 1 42.0
Item 2 43.0


Jul 18 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

49
by: Steven Bethard | last post by:
I promised I'd put together a PEP for a 'generic object' data type for Python 2.5 that allows one to replace __getitem__ style access with dotted-attribute style access (without declaring another...
3
by: .Net Newbie | last post by:
I'm new to .Net and need to create a generic (free) way to update lookup tables in SQL Server (using C#) in ASP.Net pages. I found an article at:...
5
by: Richard Brown | last post by:
Ok, I've been looking through the .NET SDK docs and stuff. I'm wondering if you can provide a control extender that does generic validation or functionality just by dropping it on the form. For...
38
by: Luke Matuszewski | last post by:
Welcome I have read the in the faq from jibbering about the generic DynWrite, but i also realized that is uses only innerHTML feature of HTML objects. (1) Is there a DOM function which is very...
15
by: David Lozzi | last post by:
Howdy, I have a function that uploads an image and that works great. I love ..Nets built in upload, so much easier than 3rd party uploaders! Now I am making a public function that will take the...
3
by: markww | last post by:
Hi, I have a wrapper around some 3rd party database library function. The pseudo code looks like the following - it is meant to open a table in a database, extract values from a table, then copy...
3
by: Seth Gecko | last post by:
Hi I am working with generic lists of various objects and a control dealing with these lists. For instance: A parent form holds: dim Walls as List(Of wall) dim Segments as List(Of segment) ...
4
by: shapper | last post by:
Hello, How can I transform a Generic List(Of String) to a string as follows: "value1,value2,value3,value4, ..." Thanks, Miguel
1
by: jlbfunes | last post by:
Hello, I am new to c++. I tried to create a function for doing the following: 1. Read a matrix from a .txt file 2. Store the retrieved data as a vector of vectors 3. Put the result in...
26
by: raylopez99 | last post by:
Here is a good example that shows generic delegate types. Read this through and you'll have an excellent understanding of how to use these types. You might say that the combination of the generic...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
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...
0
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...

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.