English 中文(简体)
Munging non-printable characters to dots using string.translate()
原标题:

So I ve done this before and it s a surprising ugly bit of code for such a seemingly simple task.

The goal is to translate any non-printable character into a . (dot). For my purposes "printable" does exclude the last few characters from string.printable (new-lines, tabs, and so on). This is for printing things like the old MS-DOS debug "hex dump" format ... or anything similar to that (where additional whitespace will mangle the intended dump layout).

I know I can use string.translate() and, to use that, I need a translation table. So I use string.maketrans() for that. Here s the best I could come up with:

filter = string.maketrans(
   string.translate(string.maketrans(  ,  ),
   string.maketrans(  ,  ),string.printable[:-5]),
    . *len(string.translate(string.maketrans(  ,  ),
   string.maketrans(  ,  ),string.printable[:-5])))

... which is an unreadable mess (though it does work).

From there you can call use something like:

for each_line in sometext:
    print string.translate(each_line, filter)

... and be happy. (So long as you don t look under the hood).

Now it is more readable if I break that horrid expression into separate statements:

ascii = string.maketrans(  ,  )   # The whole ASCII character set
nonprintable = string.translate(ascii, ascii, string.printable[:-5])  # Optional delchars argument
filter = string.maketrans(nonprintable,  .  * len(nonprintable))

And it s tempting to do that just for legibility.

However, I keep thinking there has to be a more elegant way to express this!

最佳回答

Here s another approach using a list comprehension:

filter =   .join([[ . , chr(x)][chr(x) in string.printable[:-5]] for x in xrange(256)])
问题回答

Broadest use of "ascii" here, but you get the idea

>>> import string
>>> ascii="".join(map(chr,range(256)))
>>> filter="".join(( . ,x)[x in string.printable[:-5]] for x in ascii)
>>> ascii.translate(filter)
 ................................ !"#$%& ()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~................................................................................................................................. 

If I were golfing, probably use something like this:

filter= . *32+"".join(map(chr,range(32,127)))+ . *129

for actual code-golf, I imagine you d avoid string.maketrans entirely

s=set(string.printable[:-5])
newstring =   .join(x for x in oldstring if x in s else  . )

or

newstring=re.sub( [^ +string.printable[:-5]+ ] ,  ,oldstring)

I don t find this solution ugly. It is certainly more efficient than any regex based solution. Here is a tiny bit shorter solution. But only works in python2.6:

nonprintable = string.maketrans(  ,  ).translate(None, string.printable[:-5])
filter = string.maketrans(nonprintable,  .  * len(nonprintable))




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签