I was wondering how i could parse the contents of a file into an array.
the file would look something like this:
gif:image/gif
html:text/html
jpg:image/jpeg
....
As you can see, it contains the mime type and the file extension
seperated by commas, 1 per line. I was wondering if it was possible to
create and array like this:
(Pseudocode)
mimetypearray[gif] = "image/gif"
mimetypearray[html] = "text/html"
mimetypearray[jpg] = "image/jpeg"
....
I come from a PHP backround where I know this is possible, but I am new
at Python. Please disregard this if it is a stupid question. 7 3293
> I was wondering how i could parse the contents of a file into an array. the file would look something like this:
gif:image/gif html:text/html jpg:image/jpeg
Try something like this:
d = {}
for line in open("input.txt ").readline s():
ext, mime = line.strip().sp lit(":")
d[ext] = mime
print d
Craig
amfr wrote: I was wondering how i could parse the contents of a file into an array. the file would look something like this:
gif:image/gif html:text/html jpg:image/jpeg ...
As you can see, it contains the mime type and the file extension seperated by commas, 1 per line. I was wondering if it was possible to create and array like this:
(Pseudocode) mimetypearray[gif] = "image/gif" mimetypearray[html] = "text/html" mimetypearray[jpg] = "image/jpeg" ...
You want a dictionary, not an array.
mimetypedict = {}
for line in mimetypefile:
line = line.rsplit('\r \n')
extension, mimetype = line.split(':')
mimetypedict[extension] = mimetype
Note that there's already a MIME type database in the standard mimtypes
module: <http://python.org/doc/current/lib/module-mimetypes.html> .
Thanks a lot. The webserver I am writing works now :)
Leif K-Brooks wrote: line = line.rsplit('\r \n')
Er, that should be line.rstrip, not line.rsplit.
On 14 Nov 2005 13:48:45 -0800, "amfr" <am******@gmail .com> wrote: I was wondering how i could parse the contents of a file into an array. the file would look something like this:
gif:image/gif html:text/html jpg:image/jpeg ...
As you can see, it contains the mime type and the file extension seperated by commas, 1 per line. I was wondering if it was possible to create and array like this:
(Pseudocode) mimetypearra y[gif] = "image/gif" mimetypearra y[html] = "text/html" mimetypearra y[jpg] = "image/jpeg" ...
I come from a PHP backround where I know this is possible, but I am new at Python. Please disregard this if it is a stupid question.
Pretty much anything is possible in Python, if you can conceive it well enough ;-)
Assuming f is from f = open(yourfile), simulated with StringIO file object here, from StringIO import StringIO f = StringIO("""\
... gif:image/gif
... html:text/html
... jpg:image/jpeg
... """)
And assuming that there are no spaces around the ':' or in the two pieces,
but maybe some optional whitespace at either end of a line and \n at the end
(except maybe the last line), and no blank lines, you can get a dict mapping easily:
mimetypedict = dict(tuple(line .strip().split( ':')) for line in f)
This gives you: mimetypedict
{'gif': 'image/gif', 'html': 'text/html', 'jpg': 'image/jpeg'}
Which you can access using the names as keys, e.g., mimetypedict['gif']
'image/gif'
If you want to use bare names to access the info via an object, you can use the
dict info to create a class or class instance and give it the named attributes, e.g.
a class with the data as class variables is quick:
MTC = type('MTC',(), mimetypedict) MTC.gif
'image/gif' MTC.jpg
'image/jpeg'
Or you could substitute the mimetypedict expression from above to make another one-liner ;-)
Other ways of setting up your info are certainly possible, and may be more suitable,
depending on how you intend to use the info. As mentioned, the mimetypes module
may already have much of the data and/or functionality you want.
Regards,
Bengt Richter
On 14 Nov 2005 13:48:45 -0800, "amfr" <am******@gmail .com> wrote: I was wondering how i could parse the contents of a file into an array. the file would look something like this:
gif:image/gif html:text/html jpg:image/jpeg ...
As you can see, it contains the mime type and the file extension seperated by commas, 1 per line. I was wondering if it was possible to create and array like this:
(Pseudocode) mimetypearra y[gif] = "image/gif" mimetypearra y[html] = "text/html" mimetypearra y[jpg] = "image/jpeg" ...
I come from a PHP backround where I know this is possible, but I am new at Python. Please disregard this if it is a stupid question.
Pretty much anything is possible in Python, if you can conceive it well enough ;-)
Assuming f is from f = open(yourfile), simulated with StringIO file object here, from StringIO import StringIO f = StringIO("""\
... gif:image/gif
... html:text/html
... jpg:image/jpeg
... """)
And assuming that there are no spaces around the ':' or in the two pieces,
but maybe some optional whitespace at either end of a line and \n at the end
(except maybe the last line), and no blank lines, you can get a dict mapping easily:
mimetypedict = dict(tuple(line .strip().split( ':')) for line in f)
This gives you: mimetypedict
{'gif': 'image/gif', 'html': 'text/html', 'jpg': 'image/jpeg'}
Which you can access using the names as keys, e.g., mimetypedict['gif']
'image/gif'
If you want to use bare names to access the info via an object, you can use the
dict info to create a class or class instance and give it the named attributes, e.g.
a class with the data as class variables is quick:
MTC = type('MTC',(), mimetypedict) MTC.gif
'image/gif' MTC.jpg
'image/jpeg'
Or you could substitute the mimetypedict expression from above to make another one-liner ;-)
Other ways of setting up your info are certainly possible, and may be more suitable,
depending on how you intend to use the info. As mentioned, the mimetypes module
may already have much of the data and/or functionality you want.
Regards,
Bengt Richter This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Tyaan |
last post by:
Hi.. I'm a perl noob need to know how to write a script to parse a
file containing one to four of the following blocks of text? I then
want to print the results in a format showing the memory size (128)
for each device that was found?
Structure: Memory Device (Type 17)
Type: 17
Length: 15h
Handle: 0024h (36t)
Memory Array Handle: 0021
|
by: iop |
last post by:
Hello there,
I'd like to "parse" an entire multi-dimension array like this :
APP
APP
without knowing "framework" or "config" or anything passed as variables...
'cause it's simple to call APP.length
My goal is to simply write a xml file out a javascript array...
Thanks for any help !!
|
by: Charles Law |
last post by:
Does anyone have a regex pattern to parse HTML from a stream?
I have a well structured file, where each line is of the form
<sometag someattribute='attr'>text</sometag>
for example
<SPAN CLASS='myclass'>A bit of text</SPAN>, or
Just some text, without tags
|
by: |
last post by:
Hi,
I need to read a big CSV file, where different fields should be converted to
different types,
such as int, double, datetime, SqlMoney, etc.
I have an array, which describes the fields and their types. I would like
to somehow store a reference to parsing operations in this array
(such as Int32.Parse, Double.Parse, SqlMoney.Parse, etc),
so I can invoke the appropriate one without writing a long switch.
|
by: Johnny Google |
last post by:
Here is an example of the type of data from a file I will have:
Apple,4322,3435,4653,6543,4652
Banana,6934,5423,6753,6531
Carrot,3454,4534,3434,1111,9120,5453
Cheese,4411,5522,6622,6641
The first position is the info (the product) I want to retreive for the
corresponding code. Assuming that the codes are unique for each product
and all code data is on one line.
| |
by: AdrianH |
last post by:
Assumptions
I am assuming that you know or are capable of looking up the functions I am to describe here and have some remedial understanding of C++ programming.
FYI
Although I have called this article “How to Parse a File in C++”, we are actually mostly lexing a file which is the breaking down of a stream in to its component parts, disregarding the syntax that stream contains. Parsing is actually including the syntax in order to make...
|
by: cmdolcet69 |
last post by:
How do i parse a text file with data value in it? I have a series of
values that are sepereated by commas. the file holds around 3700
values and all these values need to be parsed out and put into an
array to be used.
|
by: Bint |
last post by:
Hi,
I'm trying to parse an xml file into an array tree. From the PHP site
in the comments, I got this code. But it doesn't work for me. It's saying
that the passed variable is not an array or object in the call end($stack),
in the first function startElement(). Anyone know why that would be?
$stack is an array, as far as I can tell.
Thanks
B
|
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,...
|
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
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...
| |
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,...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
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...
|
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 then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |