473,757 Members | 8,356 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Filtering out non-readable characters

I have a file with binary and ascii characters in it. I massage the
data and convert it to a more readable format, however it still comes
up with some binary characters mixed in. I'd like to write something
to just replace all non-printable characters with '' (I want to delete
non-printable characters).

I am having trouble figuring out an easy python way to do this... is
the easiest way to just write some regular expression that does
something like replace [^\p] with ''?

Or is it better to go through every character and do ord(character),
check the ascii values?

What's the easiest way to do something like this?

thanks

Jul 21 '05
19 4576
On Sat, 16 Jul 2005 16:42:58 -0400, Peter Hansen wrote:
Steven D'Aprano wrote:
On Sat, 16 Jul 2005 10:25:29 -0400, Peter Hansen wrote:
Bengt Richter wrote:

>>> identity = ''.join([chr(i) for i in xrange(256)])

And note that with Python 2.4, in each case the above square brackets
are unnecessary (though harmless), because of the arrival of "generator
expression s" in the language.


But to use generator expressions, wouldn't you need an extra pair of round
brackets?

eg identity = ''.join( ( chr(i) for i in xrange(256) ) )


Come on, Steven. Don't tell us you didn't have access to a Python
interpreter to check before you posted:


Er, as I wrote in my post:

"Steven
who is still using Python 2.3, and probably will be for quite some time"

So, no, I didn't have access to a Python interpreter running version 2.4.

I take it then that generator expressions work quite differently
than list comprehensions? The equivalent "implied delimiters" for a list
comprehension would be something like this:
L = [1, 2, 3]
L[ i for i in range(2) ] File "<stdin>", line 1
L[ i for i in range(2) ]
^
SyntaxError: invalid syntax

which is a very different result from:
L[ [i for i in range(2)] ]

Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: list indices must be integers

In other words, a list comprehension must have the [ ] delimiters to be
recognised as a list comprehension, EVEN IF the square brackets are there
from some other element. But a generator expression doesn't care where the
round brackets come from, so long as they are there: they can be part of
the function call.

I hope that makes sense to you.
--
Steven

Jul 21 '05 #11
On Sat, 16 Jul 2005 19:01:50 -0400, Peter Hansen wrote:
George Sakkis wrote:
"Bengt Richter" <bo**@oz.net> wrote:
>>> identity = ''.join([chr(i) for i in xrange(256)])


Or equivalently:
>identity = string.maketran s('','')


Wow! That's handy, not to mention undocumented. (At least in the
string module docs.) Where did you learn that, George?


I can't answer for George, but I also noticed that behaviour. I discovered
it by trial and error. I thought, oh what a nuisance that the arguments
for maketrans had to include all 256 characters, then I wondered what
error you would get if you left some out, and discovered that you didn't
get an error at all.

That actually disappointed me at the time, because I was looking for
behaviour where the missing characters weren't filled in, but I've come to
appreciate it since.
--
Steven
Jul 21 '05 #12
Steven D'Aprano wrote:
On Sat, 16 Jul 2005 16:42:58 -0400, Peter Hansen wrote:
Come on, Steven. Don't tell us you didn't have access to a Python
interpreter to check before you posted:


Er, as I wrote in my post:

"Steven
who is still using Python 2.3, and probably will be for quite some time"


Sorry, missed that! I don't generally notice signatures much, partly
because Thunderbird is smart enough to "grey them out" (the main text is
displayed as black, quoted material in blue, and signatures in a light
gray.)

I don't have a firm answer (though I suspect the language reference
does) about when "dedicated" parentheses are required around a generator
expression. I just know that, so far, they just work when I want them
to. Like most of Python. :-)

-Peter
Jul 21 '05 #13
Bengt Richter wrote:
Thanks for the nudge. Actually, I know about generator expressions, but
at some point I must have misinterpreted some bug in my code to mean
that join in particular didn't like generator expression arguments,
and wanted lists.


I suspect this is bug 905389 [1]:
def gen(): .... yield 1
.... raise TypeError('from gen()')
.... ''.join([x for x in gen()]) Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
File "<interacti ve input>", line 3, in gen
TypeError: from gen() ''.join(x for x in gen())

Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
TypeError: sequence expected, generator found

I run into this every month or so, and have to remind myself that it
means that my generator is raising a TypeError, not that join doesn't
accept generator expressions...

STeVe

[1] http://www.python.org/sf/905389
Jul 21 '05 #14
Peter Hansen wrote:
''.join(chr(c) for c in range(65, 91))

'ABCDEFGHIJKLMN OPQRSTUVWXYZ'


Wouldn't this be a candidate for making the Python language stricter?

Do you remember old Python versions treating l.append(n1,n2) the same
way like l.append((n1,n2 )). I'm glad this is forbidden now.

Ciao, Michael.
Jul 21 '05 #15
Michael Ströder wrote:
Peter Hansen wrote:
>''.join(ch r(c) for c in range(65, 91))


'ABCDEFGHIJKL MNOPQRSTUVWXYZ'

Wouldn't this be a candidate for making the Python language stricter?


Why would that be true? I believe str.join() takes any iterable, and a
generator (as returned by a generator expression) certainly qualifies.

-Peter
Jul 21 '05 #16
Michael Ströder wrote:
Peter Hansen wrote:
>''.join(ch r(c) for c in range(65, 91))


'ABCDEFGHIJKL MNOPQRSTUVWXYZ'


Wouldn't this be a candidate for making the Python language stricter?

Do you remember old Python versions treating l.append(n1,n2) the same
way like l.append((n1,n2 )). I'm glad this is forbidden now.


That wasn't a syntax issue; it was an API issue. list.append() allowed
multiple arguments and interpreted them as if they were a single tuple.
That was confusing and unnecessary.

Allowing generator expressions to forgo extra parentheses where they
aren't required is something different, and in my opinion, a good thing.

--
Robert Kern
rk***@ucsd.edu

"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter

Jul 21 '05 #17
On 15 Jul 2005 17:33:39 -0700, "MKoool" <mo***@teraboli c.com> wrote:
I have a file with binary and ascii characters in it. I massage the
data and convert it to a more readable format, however it still comes
up with some binary characters mixed in. I'd like to write something
to just replace all non-printable characters with '' (I want to delete
non-printable characters).

I am having trouble figuring out an easy python way to do this... is
the easiest way to just write some regular expression that does
something like replace [^\p] with ''?

Or is it better to go through every character and do ord(character),
check the ascii values?

What's the easiest way to do something like this?

thanks


Easiest way is open the file with EdXor (freeware editor), select all,
Format > Wipe Non-Ascii.

Ok it's not python, but it's the easiest.
Jul 21 '05 #18
On Tue, 19 Jul 2005 20:28:31 +1200, Ross wrote:
On 15 Jul 2005 17:33:39 -0700, "MKoool" <mo***@teraboli c.com> wrote:
I have a file with binary and ascii characters in it. I massage the
data and convert it to a more readable format, however it still comes
up with some binary characters mixed in. I'd like to write something
to just replace all non-printable characters with '' (I want to delete
non-printable characters).

I am having trouble figuring out an easy python way to do this... is
the easiest way to just write some regular expression that does
something like replace [^\p] with ''?

Or is it better to go through every character and do ord(character),
check the ascii values?

What's the easiest way to do something like this?

thanks


Easiest way is open the file with EdXor (freeware editor), select all,
Format > Wipe Non-Ascii.

Ok it's not python, but it's the easiest.


1 Open Internet Explorer
2 Go to Google
3 Search for EdXor
4 Browser locks up
5 Force quit with ctrl-alt-del
6 Run anti-virus program
7 Download new virus definitions
8 Remove viruses
9 Run anti-spyware program
10 Download new definitions
11 Remove spyware
12 Open Internet Explorer
13 Download Firefox
14 Install Firefox
15 Open Firefox
16 Go to Google
17 Search for EdXor
18 Download application
19 Run installer
20 Reboot
21 Run EdXor
22 Open file
23 Select all
24 Select Format>Wipe Non-ASCII
25 Select Save
26 Quit EdXor

Hmmm. Perhaps not *quite* the easiest way :-)

--
Steven.

Jul 21 '05 #19
On Sun, 17 Jul 2005 15:42:08 -0600, Steven Bethard <st************ @gmail.com> wrote:
Bengt Richter wrote:
Thanks for the nudge. Actually, I know about generator expressions, but
at some point I must have misinterpreted some bug in my code to mean
that join in particular didn't like generator expression arguments,
and wanted lists.


I suspect this is bug 905389 [1]:
def gen():... yield 1
... raise TypeError('from gen()')
... ''.join([x for x in gen()])Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
File "<interacti ve input>", line 3, in gen
TypeError: from gen() ''.join(x for x in gen())

Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
TypeError: sequence expected, generator found

I run into this every month or so, and have to remind myself that it
means that my generator is raising a TypeError, not that join doesn't
accept generator expressions...

STeVe

[1] http://www.python.org/sf/905389


That must have been it, thanks.

Regards,
Bengt Richter
Jul 24 '05 #20

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

Similar topics

0
1724
by: William Park | last post by:
1. Here is shell version of Python filter() for array. Essentially, you apply a command on each array element, and extract only those elements which it returns success (0). This is specialized form of list comprehension where you can contruct an array from another array, using some sort of test or filtering. Usage is arrayfilter command array where 'command' is a function, shell script, or external executable, which takes one...
13
3889
by: kevinold | last post by:
Hello everyone, I have a list of about 1600 employees that I'd like to have displayed in a form. I'd like to make the "search" for the user as easy as possible. I ran across this: http://www.barelyfitz.com/projects/filterlist/ filter that works quite well with small lists (on the site is a list of 20 names). It also works quite well in Firefox 1.5, but crawls in IE 6.
3
11104
by: Jason | last post by:
I am trying to filter records in a primary form based on records in related tables. The data in the related tables is being displayed in the primary form through subforms. To be more specific, I have a primary form named TestResults, which is connected to data in a table named TestResults. There are basically two other tables that are related to the TestResults table (and the primary form) named Names-Normalized and SiteAddresses. The...
2
1891
by: Tarvos{k} | last post by:
Greetings, I am working on importing some info from excel to Access and have run into a problem. There are some entries in the ZipCode field that are not in numeric form. I can't seem to find a way to filter out the non numeric one, and would really appreciate some help. The problem is that the ones that aren't correct are shown like this "999XX" (obviously without the quotes) where the "9" could be any number and the "X" could be any...
7
14816
by: | last post by:
Hello, Does anyone have an idea on how I can filter the data in the gridview control that was returned by an sql query? I have a gridview that works fine when I populate it with data. Now I want to look at that data and filter it based on what is in it. I know that this could have been done with data sets and data views in asp.net 1.1 but how is this done now in asp.net 2.0?
2
1444
by: Andrew Poulos | last post by:
A friend of mine has built as simple site for use on his company's intranet. It uses JavaScript to read comma-delimited information from a text file and displays it in tabular form. When I looked at the source there is js like this: function forwardClick() { if (sitelist.recordset.AbsolutePosition != sitelist.recordset.RecordCount) { sitelist.recordset.moveNext();
2
3094
by: JUAN ERNESTO FLORES BELTRAN | last post by:
Hi you all, I am developping a python application which connects to a database (postresql) and displays the query results on a treeview. In adittion to displaying the info i do need to implement filtering facility for all the columns of the treestore/liststore model in order to allow the user an easy search method to find the desired information. The treestore is created with information related to cars, the columns are:
7
16458
by: Ryan | last post by:
I have a DataGridView which displays numeric (Int32) data from an underlying database. I want the numbers to be displayed in numeric format "#,###" (with commas). I want to also limit the user so they can only input numerical values. Is there any way to do this? Currently my formatting works but if the user enters a value manually the formatting is not applied to the new value. Also I haven't found a way to allow only numerical input....
0
3131
by: Yarik | last post by:
Hello, Here is a sample (and very simple) code that binds an Access 2003 form to a fabricated ADO recordset: ' Create recordset... Dim rs As ADODB.Recordset: Set rs = New ADODB.Recordset ' Append one or more fields... Call rs.Fields.Append("Number", adInteger)
2
1303
by: =?Utf-8?B?amV6MTIzNDU2?= | last post by:
Hi ASP.Net experts I have a archived SQL Server 2000 database table with about 300,000 records, and need to display filtered data on a ASP.Net 2 web page. Basic filtering needs to be done on id, name and DOB fields, however, advanced filtering could include between 1 and 10 different checkboxes being check or unchecked. What would be the best approach to this. Are there any examples I could view?
0
9489
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
10072
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, 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...
0
9906
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
9885
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,...
1
7286
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
6562
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();...
0
5329
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3829
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 we have to send another system
3
2698
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.