473,473 Members | 2,122 Online
Bytes | Software Development & Data Engineering Community
Create 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 #1
19 4548
On 15 Jul 2005 17:33:39 -0700, "MKoool" <mo***@terabolic.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?

import string
string.printable '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLM NOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c' identity = ''.join([chr(i) for i in xrange(256)])
unprintable = ''.join([c for c in identity if c not in string.printable])

def remove_unprintable(s): ... return s.translate(identity, unprintable)
... set(remove_unprintable(identity)) - set(string.printable) set([]) set(remove_unprintable(identity)) set(['\x0c', ' ', '$', '(', ',', '0', '4', '8', '<', '@', 'D', 'H', 'L', 'P', 'T', 'X', '\\', '`
', 'd', 'h', 'l', 'p', 't', 'x', '|', '\x0b', '#', "'", '+', '/', '3', '7', ';', '?', 'C', 'G',
'K', 'O', 'S', 'W', '[', '_', 'c', 'g', 'k', 'o', 's', 'w', '{', '\n', '"', '&', '*', '.', '2',
'6', ':', '>', 'B', 'F', 'J', 'N', 'R', 'V', 'Z', '^', 'b', 'f', 'j', 'n', 'r', 'v', 'z', '~', '
\t', '\r', '!', '%', ')', '-', '1', '5', '9', '=', 'A', 'E', 'I', 'M', 'Q', 'U', 'Y', ']', 'a',
'e', 'i', 'm', 'q', 'u', 'y', '}']) sorted(set(remove_unprintable(identity))) == sorted(set(string.printable)) True sorted((remove_unprintable(identity))) == sorted((string.printable)) True

After that, to get clean file text, something like

cleantext = remove_unprintable(file('unclean.txt').read())

should do it. Or you should be able to iterate by lines something like (untested)

for uncleanline in file('unclean.txt'):
cleanline = remove_unprintable(uncleanline)
# ... do whatever with clean line

If there is something in string.printable that you don't want included, just use your own
string of printables. BTW,
help(str.translate)

Help on method_descriptor:

translate(...)
S.translate(table [,deletechars]) -> string

Return a copy of the string S, where all characters occurring
in the optional argument deletechars are removed, and the
remaining characters have been mapped through the given
translation table, which must be a string of length 256.

Regards,
Bengt Richter
Jul 21 '05 #2
Wow, that was the most thorough answer to a comp.lang.python question
since the Martellibot got busy in the search business.

Jul 21 '05 #3
Bengt Richter wrote:
>>> identity = ''.join([chr(i) for i in xrange(256)])
>>> unprintable = ''.join([c for c in identity if c not in string.printable])


And note that with Python 2.4, in each case the above square brackets
are unnecessary (though harmless), because of the arrival of "generator
expressions" in the language. (Bengt knows this already, of course, but
his brain is probably resisting the reprogramming. :-) )

-Peter
Jul 21 '05 #4
On Sat, 16 Jul 2005 10:25:29 -0400, Peter Hansen wrote:
Bengt Richter wrote:
>>> identity = ''.join([chr(i) for i in xrange(256)])
>>> unprintable = ''.join([c for c in identity if c not in string.printable])


And note that with Python 2.4, in each case the above square brackets
are unnecessary (though harmless), because of the arrival of "generator
expressions" 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) ) )

with the extra spaces added for clarity.

That is, the brackets after join make the function call, and the nested
brackets make the generator. That, at least, is my understanding.

--
Steven
who is still using Python 2.3, and probably will be for quite some time
Jul 21 '05 #5
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
expressions" 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:

c:\>python
Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32
''.join(chr(c) for c in range(65, 91))

'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

-Peter
Jul 21 '05 #6
On Sat, 16 Jul 2005 10:25:29 -0400, Peter Hansen <pe***@engcorp.com> wrote:
Bengt Richter wrote:
>>> identity = ''.join([chr(i) for i in xrange(256)])
>>> unprintable = ''.join([c for c in identity if c not in string.printable])


And note that with Python 2.4, in each case the above square brackets
are unnecessary (though harmless), because of the arrival of "generator
expressions" in the language. (Bengt knows this already, of course, but
his brain is probably resisting the reprogramming. :-) )

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. Actually it seems to like anything at all that can
be iterated produce a sequence of strings. So I'm glad to find that
join is fine after all, and to get that misap[com?:-)]prehension
out of my mind ;-)

Regards,
Bengt Richter
Jul 21 '05 #7
"Bengt Richter" <bo**@oz.net> wrote:
>>> identity = ''.join([chr(i) for i in xrange(256)])
>>> unprintable = ''.join([c for c in identity if c not in string.printable])
Or equivalently:
identity = string.maketrans('','')
unprintable = identity.translate(identity, string.printable)


George
Jul 21 '05 #8
George Sakkis wrote:
"Bengt Richter" <bo**@oz.net> wrote:
>>> identity = ''.join([chr(i) for i in xrange(256)])
Or equivalently:identity = string.maketrans('','')


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

-Peter
Jul 21 '05 #9
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
expressions" 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 #10
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.maketrans('','')


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 #11
Replying to myself... this is getting to be a habit.

On Sun, 17 Jul 2005 15:08:12 +1000, Steven D'Aprano wrote:
I hope that makes sense to you.


That wasn't meant as a snide little dig at Peter, and I'm sorry if anyone
reads it that way. I found myself struggling to explain simply the
different behaviour between list comps and generator expressions, and
couldn't be sure I was explaining myself as clearly as I wanted. It might
have been better if I had left off the "to you".

--
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 "<interactive input>", line 1, in ?
File "<interactive input>", line 3, in gen
TypeError: from gen() ''.join(x for x in gen())

Traceback (most recent call last):
File "<interactive 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))

'ABCDEFGHIJKLMNOPQRSTUVWXYZ'


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(chr(c) for c in range(65, 91))


'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

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(chr(c) for c in range(65, 91))


'ABCDEFGHIJKLMNOPQRSTUVWXYZ'


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***@terabolic.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***@terabolic.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 "<interactive input>", line 1, in ?
File "<interactive input>", line 3, in gen
TypeError: from gen() ''.join(x for x in gen())

Traceback (most recent call last):
File "<interactive 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
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...
13
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:...
3
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...
2
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...
7
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...
2
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...
2
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...
7
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...
0
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 '...
2
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...
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,...
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...
0
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...
0
agi2029
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,...
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: 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 ...
0
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.