473,804 Members | 3,380 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Reading files, splitting on a delimiter and newlines.

Hello,

I have a situation where I have a file that contains text similar to:

myValue1 = contents of value1
myValue2 = contents of value2 but
with a new line here
myValue3 = contents of value3

My first approach was to open the file, use readlines to split the
lines on the "=" delimiter into a key/value pair (to be stored in a
dict).

After processing a couple files I noticed its possible that a newline
can be present in the value as shown in myValue2.

In this case its not an option to say remove the newlines if its a
"multi line" value as the value data needs to stay intact.

I'm a bit confused as how to go about getting this to work.

Any suggestions on an approach would be greatly appreciated!

Jul 25 '07 #1
6 2543
On Jul 25, 10:46 am, chris...@gmail. com wrote:
Hello,

I have a situation where I have a file that contains text similar to:

myValue1 = contents of value1
myValue2 = contents of value2 but
with a new line here
myValue3 = contents of value3

My first approach was to open the file, use readlines to split the
lines on the "=" delimiter into a key/value pair (to be stored in a
dict).

After processing a couple files I noticed its possible that a newline
can be present in the value as shown in myValue2.

In this case its not an option to say remove the newlines if its a
"multi line" value as the value data needs to stay intact.

I'm a bit confused as how to go about getting this to work.

Any suggestions on an approach would be greatly appreciated!
I'm confused. You don't want the newline to be present, but you can't
remove it because the data has to stay intact? If you don't want to
change it, then what's the problem?

Mike

Jul 25 '07 #2
On Wed, 25 Jul 2007 09:16:26 -0700, kyosohma wrote:
On Jul 25, 10:46 am, chris...@gmail. com wrote:
>Hello,

I have a situation where I have a file that contains text similar to:

myValue1 = contents of value1
myValue2 = contents of value2 but
with a new line here
myValue3 = contents of value3

My first approach was to open the file, use readlines to split the
lines on the "=" delimiter into a key/value pair (to be stored in a
dict).

After processing a couple files I noticed its possible that a newline
can be present in the value as shown in myValue2.

In this case its not an option to say remove the newlines if its a
"multi line" value as the value data needs to stay intact.

I'm a bit confused as how to go about getting this to work.

Any suggestions on an approach would be greatly appreciated!

I'm confused. You don't want the newline to be present, but you can't
remove it because the data has to stay intact? If you don't want to
change it, then what's the problem?

Mike
It's obviously that simple line-by-line filtering won't handle multi-line
statements.

You could solve that by saving the last item you added something to and,
if the line currently handles doesn't look like an assignment, append it
to this item. You might run into problems with such data:

foo = modern maths
proved that 1 = 1
bar = single

If your dataset always has indendation on subsequent lines, you might use
this. Or if the key's name is always just one word.

HTH,
Stargaming
Jul 25 '07 #3
On Jul 26, 3:08 am, Stargaming <stargam...@gma il.comwrote:
On Wed, 25 Jul 2007 09:16:26 -0700, kyosohma wrote:
On Jul 25, 10:46 am, chris...@gmail. com wrote:
Hello,
I have a situation where I have a file that contains text similar to:
myValue1 = contents of value1
myValue2 = contents of value2 but
with a new line here
myValue3 = contents of value3
My first approach was to open the file, use readlines to split the
lines on the "=" delimiter into a key/value pair (to be stored in a
dict).
After processing a couple files I noticed its possible that a newline
can be present in the value as shown in myValue2.
In this case its not an option to say remove the newlines if its a
"multi line" value as the value data needs to stay intact.
I'm a bit confused as how to go about getting this to work.
Any suggestions on an approach would be greatly appreciated!
I'm confused. You don't want the newline to be present, but you can't
remove it because the data has to stay intact? If you don't want to
change it, then what's the problem?
Mike

It's obviously that simple line-by-line filtering won't handle multi-line
statements.

You could solve that by saving the last item you added something to and,
if the line currently handles doesn't look like an assignment, append it
to this item. You might run into problems with such data:

foo = modern maths
proved that 1 = 1
bar = single

If your dataset always has indendation on subsequent lines, you might use
this. Or if the key's name is always just one word.
My take: all of the above, plus: Given that you want to extract stuff
of the form <LHS= <RHSI'd suggest developing a fairly precise
regular expression for LHS, maybe even for RHS, and trying this on as
many of these files as you can.

Why an RE for RHS? Consider:

foo = somebody said "I think that
REs = trouble
maybe_better = pyparsing"

:-)

Jul 25 '07 #4
On Jul 25, 8:46 am, chris...@gmail. com wrote:
Hello,

I have a situation where I have a file that contains text similar to:

myValue1 = contents of value1
myValue2 = contents of value2 but
with a new line here
myValue3 = contents of value3

My first approach was to open the file, use readlines to split the
lines on the "=" delimiter into a key/value pair (to be stored in a
dict).

After processing a couple files I noticed its possible that a newline
can be present in the value as shown in myValue2.

In this case its not an option to say remove the newlines if its a
"multi line" value as the value data needs to stay intact.

I'm a bit confused as how to go about getting this to work.

Any suggestions on an approach would be greatly appreciated!


Check the length of the list returned from split; this allows
your to append to the previously extracted value if need be.

import StringIO
import pprint

buf = """\
myValue1 = contents of value1
myValue2 = contents of value2 but
with a new line here
myValue3 = contents of value3
"""

mockfile = StringIO.String IO(buf)

record=dict()

for line in mockfile:
kvpair = line.split('=', 2)
if len(kvpair) == 2:
key, value = kvpair
record[key] = value
else:
record[key] += line

pprint.pprint(r ecord)

# lstrip() to remove newlines if needed ...

--
Hope this helps,
Steven

Jul 26 '07 #5
: <kyo...ma@gmail .comWrote:
On Jul 25, 10:46 am, chris...@gmail. com wrote:
Hello,

I have a situation where I have a file that contains text similar to:

myValue1 = contents of value1
myValue2 = contents of value2 but
with a new line here
myValue3 = contents of value3

My first approach was to open the file, use readlines to split the
lines on the "=" delimiter into a key/value pair (to be stored in a
dict).

After processing a couple files I noticed its possible that a newline
can be present in the value as shown in myValue2.

In this case its not an option to say remove the newlines if its a
"multi line" value as the value data needs to stay intact.

I'm a bit confused as how to go about getting this to work.

Any suggestions on an approach would be greatly appreciated!

I'm confused. You don't want the newline to be present, but you can't
remove it because the data has to stay intact? If you don't want to
change it, then what's the problem?
I think the OP's trouble is that the value he wants gets split up by the
newline at the end of the line when he uses readline().

One can try adding the single value to the previous value in the previous
key/value pair when the split does not yield two values - a bit hackish,
but given structured input data it might work.

- Hendrik

Jul 26 '07 #6
ch******@gmail. com a écrit :
Hello,

I have a situation where I have a file that contains text similar to:

myValue1 = contents of value1
myValue2 = contents of value2 but
with a new line here
myValue3 = contents of value3

My first approach was to open the file, use readlines to split the
lines on the "=" delimiter into a key/value pair (to be stored in a
dict).

After processing a couple files I noticed its possible that a newline
can be present in the value as shown in myValue2.

In this case its not an option to say remove the newlines if its a
"multi line" value as the value data needs to stay intact.

I'm a bit confused as how to go about getting this to work.

Any suggestions on an approach would be greatly appreciated!
data = {}
key = None
for line in open('yourfile. txt'):
line = line.strip()
if not line:
# skip empty lines
continue
if '=' in line:
key, value = map(str.strip, line.split('=', 1))
data[key] = value
elif key is None:
# first line without a '='
raise ValueError("inv alid format")
else:
# multiline
data[key] += "\n" + line
print data
={'myValue3': 'contents of value3', 'myValue2': 'contents of value2
but\nwith a new line here', 'myValue1': 'contents of value1'}

HTH
Jul 26 '07 #7

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

Similar topics

3
3309
by: Sandman | last post by:
I am splitting a text block into paragraphs, to be able to add images and stuff like that to a specific paragraph in a content management system. Well, right now I'm splittin on two or more newlines, so this text block: Hello, my nickname is Sandman and I am coding some PHP Call me
7
2238
by: qwweeeit | last post by:
Hi all, I am writing a script to visualize (and print) the web references hidden in the html files as: '<a href="web reference"> underlined reference</a>' Optimizing my code, I found that an essential step is: splitting on a word (in this case 'href'). I am asking if there is some alternative (more pythonic...): # SplitMultichar.py
8
1675
by: Anthony Liu | last post by:
I have this simple string: mystr = 'this_NP is_VL funny_JJ' I want to split it and give me a list as 1. I tried mystr.split('_| '), but this gave me:
9
6694
by: Yaro | last post by:
Hello DB2/NT 8.1.3 Sorry for stupid questions. I am newbe in DB2. 1. How can I read *.sql script (with table and function definitions) into a database? Tool, command... 2. In Project Center I created funcion CREATE FUNCTION DB2ADMIN.xxx( )
21
3831
by: Rohith | last post by:
I need to split a large binary file into two binary files. I have a delimiter (say NewLine) in the binaryfile. I need to split the binary file such that the first file is upto the NewLine and the Second file is from NewLine to end of file. Kindly let me know whether this si possible Thanks Rohith
1
1371
by: Gustav | last post by:
Hi! I use a regex (?<!\\?)('|\\+|:) to split a string to a String. The String i get after splitting is correctly splitted but contains all the delimiters i use to decide where the string should be splitted. Do I have to loop through the array and find every index containing a single delimiter or is there a easier way to do this.
10
8362
by: Tyler | last post by:
Hello All: After trying to find an open source alternative to Matlab (or IDL), I am currently getting acquainted with Python and, in particular SciPy, NumPy, and Matplotlib. While I await the delivery of Travis Oliphant's NumPy manual, I have a quick question (hopefully) regarding how to read in Fortran written data. The data files are not binary, but ASCII text files with no formatting and mixed data types (strings, integers,...
2
3277
by: shadow_ | last post by:
Hi i m new at C and trying to write a parser and a string class. Basicly program will read data from file and splits it into lines then lines to words. i used strtok function for splitting data to lines it worked quite well but srttok isnot working for multiple blank or commas. Can strtok do this kind of splitting if it cant what should i use . Unal
18
34855
jhardman
by: jhardman | last post by:
Have you ever wanted to upload files through a form and thought, "I'd really like to use ASP, it surely has that capability, but the tutorial I used to learn ASP didn't mention how to do this."? Have you looked around trying to find simple solutions but didn't want to wade through pages of complex code? Have you balked at paying for premade solutions that are probably overkill for your particular project? I'd like to walk you through the...
0
9706
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9579
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10330
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10319
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10076
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7616
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5520
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5651
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2990
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.