473,729 Members | 2,353 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 #1
19 4572
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?

import string
string.printabl e '0123456789abcd efghijklmnopqrs tuvwxyzABCDEFGH IJKLMNOPQRSTUVW XYZ!"#$%&\'()*+ ,-./:;<=>?@[\\]^_`{|}~ \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.printabl e])

def remove_unprinta ble(s): ... return s.translate(ide ntity, unprintable)
... set(remove_unpr intable(identit y)) - set(string.prin table) set([]) set(remove_unpr intable(identit y)) 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(remo ve_unprintable( identity))) == sorted(set(stri ng.printable)) True sorted((remove_ unprintable(ide ntity))) == sorted((string. printable)) True

After that, to get clean file text, something like

cleantext = remove_unprinta ble(file('uncle an.txt').read() )

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

for uncleanline in file('unclean.t xt'):
cleanline = remove_unprinta ble(uncleanline )
# ... do whatever with clean line

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

Help on method_descript or:

translate(...)
S.translate(tab le [,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.pytho n 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.printabl e])


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.printabl e])


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))

'ABCDEFGHIJKLMN OPQRSTUVWXYZ'

-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.printabl e])


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.printabl e])
Or equivalently:
identity = string.maketran s('','')
unprintable = identity.transl ate(identity, string.printabl e)


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.maketran s('','')


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
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 #10

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

Similar topics

0
1723
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
3885
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
11103
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
1890
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
14811
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
1442
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
3092
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
16453
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
3130
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
1302
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
8917
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
8761
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
9426
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
9142
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...
0
8148
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, 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...
0
6022
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
4525
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
4795
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3238
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

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.