首页 \ 问答 \ 如何在Python中替换字符串中的无效unicode字符?(How to replace invalid unicode characters in a string in Python?)

如何在Python中替换字符串中的无效unicode字符?(How to replace invalid unicode characters in a string in Python?)

据我所知,python的概念只在字符串中包含有效字符,但在我的情况下,操作系统将在我必须处理的路径名中提供带有无效编码的字符串。 所以我最终得到的字符串包含非unicode字符。

为了纠正这些问题,我需要以某种方式显示这些字符串。 不幸的是我无法打印它们因为它们包含非unicode字符。 是否有一种优雅的方式来以某种方式替换这些字符,至少可以了解字符串的内容?

我的想法是逐字符处理这些字符串,并检查存储的字符是否实际上是有效的unicode。 如果字符无效,我想使用某个unicode符号。 但是我怎么能这样做呢? 使用codecs似乎不适合这个目的:我已经有一个由操作系统返回的字符串,而不是字节数组。 将字符串转换为字节数组似乎涉及解码,当然我的情况会失败。 所以我似乎陷入困境。

你有一个提示,如何能够创建这样的替换字符串?


As far as I know it is the concept of python to have only valid characters in a string, but in my case the OS will deliver strings with invalid encodings in path names I have to deal with. So I end up with strings that contain characters that are non-unicode.

In order to correct these problems I need to display these strings somehow. Unfortunately I can not print them because they contain non-unicode characters. Is there an elegant way to replace these characters somehow to at least get some idea of the content of the string?

My idea would be to process these strings character by character and check if the character stored is actually valid unicode. In case of an invalid character I would like to use a certain unicode symbol. But how can I do this? Using codecs seems not to be suitable for that purpose: I already have a string, returned by the operating system, and not a byte array. Converting a string to byte array seems to involve decoding which will fail in my case of course. So it seems that I'm stuck.

Do you have an tips for me how to be able to create such a replacement string?


原文:https://stackoverflow.com/questions/38564456
更新时间:2022-04-09 12:04

最满意答案

当你有一些与异步事件循环不兼容的阻塞任务时,你必须把它放在一个单独的线程中。

如果你将有无限数量的阻塞任​​务,你想使用线程池。

无论哪种方式,您都希望有一个封装异步任务,阻止来自线程任务的通知。

最简单的方法是使用像tornado-threadpool这样的预建库。然后,你只需要这样做:

class LongHandler(tornado.web.RequestHandler):
    @thread_pool.in_thread_pool
    def long_time_function(self, callback):
        time.sleep(5)
        callback("foo")

如果你想自己做, 这个要点展示了你必须做的一个例子 - 或者,当然,各种Tornado线程池库的源代码可以作为示例代码。

只要记住Python GIL的局限性:如果你的后台任务是CPU绑定的(并且在Python中执行大部分工作,而不是在C里扩展,像释放GIL一样),你必须把它放在一个单独的过程。 对Tornado进程池库的快速搜索没有多少好的选择,但是调整线程池代码来处理池代码在Python中通常非常简单。**


*请注意,我并不特别推荐该库; 这只是Google搜索中出现的第一件事情,并且快速浏览它看起来可用且正确。

**这通常与使用concurrent.futures.ProcessPoolExecutor或具有multiprocessing.Pool替换concurrent.futures.ThreadPoolExecutor一样简单。 唯一的技巧是确保所有的任务参数和返回值都很小并且可以选择。


When you have some blocking task that doesn't play nice with the async event loop, you have to put it in a separate thread.

If you're going to have an unbounded number of blocking tasks, you want to use a thread pool.

Either way, you want to have a wrapper async task that blocks on notification from the threaded task.

The easiest way to do this is to use a pre-built library like tornado-threadpool.* Then, you just do something like this:

class LongHandler(tornado.web.RequestHandler):
    @thread_pool.in_thread_pool
    def long_time_function(self, callback):
        time.sleep(5)
        callback("foo")

If you want to do it yourself, this gist shows an example of what you have to do—or, of course, the source code for the various Tornado threadpool libraries can serve as sample code.

Just keep in mind the limitations of the Python GIL: If your background task is CPU-bound (and does most of the work in Python, rather than in a C extension that releases the GIL like numpy), you have to put it in a separate process. A quick search for Tornado process pool libraries didn't turn up as many nice options, but adapting thread pool code to process pool code is usually very easy in Python.**


* Note that I'm not specifically recommending that library; it's just the first thing that came up in a Google search, and it looks usable and correct from a quick glance.

** It's often as simple as replacing concurrent.futures.ThreadPoolExecutor with concurrent.futures.ProcessPoolExecutor or multiprocessing.dummy.Pool with multiprocessing.Pool. The only trick is to make sure that all of your task arguments and return values are small and pickleable.

相关问答

更多
  • 经过一番实验后,我能够自己弄清楚。 on_finish()永远不会被调用,因为我需要调用finish(),并且on_connection_close()永远不会调用,因为它不是一个协程。 我能够通过使用关键字yield来解决我的问题。 更多信息可以在这里找到: http : //www.tornadoweb.org/en/stable/guide/coroutines.html I was able to figure it out myself, after some experimentation. o ...
  • http://github.com/driftx/Telephus上有一个Twisted Cassandra客户端。 我想你需要为龙卷风写出类似的东西。 (切换到Twisted可能更容易。:) There is a Twisted Cassandra client at http://github.com/driftx/Telephus. I imagine you'd need to write something like that for Tornado. (Switching to Twisted ...
  • 有一个服务器和一个webframework。 我们什么时候应该使用框架,什么时候可以用其他的替换? 这个区别有点模糊。 只有当您提供静态页面时,才能使用像lighthttpd这样的快速服务器。 其他明智之举,大多数服务器提供了不同的复杂框架来开发Web应用程序。 龙卷风是一个很好的网络框架。 Twisted更有能力,被认为是一个很好的网络框架。 它支持许多协议。 Tornado和Twisted是提供支持非阻塞,异步Web /网络应用程序开发的框架。 什么时候应该使用龙卷风? 什么时候没用? 使用时应考虑什么 ...
  • 似乎我应该使用不同的浏览器或隐身窗口。 Seems i should have used a different browser or an incognito window.
  • 当你有一些与异步事件循环不兼容的阻塞任务时,你必须把它放在一个单独的线程中。 如果你将有无限数量的阻塞任务,你想使用线程池。 无论哪种方式,您都希望有一个封装异步任务,阻止来自线程任务的通知。 最简单的方法是使用像tornado-threadpool这样的预建库。然后,你只需要这样做: class LongHandler(tornado.web.RequestHandler): @thread_pool.in_thread_pool def long_time_function(self, ...
  • 我写了基于线程和队列的解决方案。 每个龙卷风过程一个线程。 该线程是一名工作人员,从队列中获取电子邮件,然后通过SMTP发送。 您通过将其添加到队列中来发送来自龙卷风应用程序的电子邮件。 简单而简单。 以下是GitHub上的示例代码: 链接 I wrote solution based on threads and queue. One thread per tornado process. This thread is a worker, gets email from queue and then se ...
  • @asynchronous装饰器应该用于标记已经异步的方法; 它不会使方法异步。 这个post方法是同步的,因为它在将控制权返回给IOLoop之前完成了它要做的所有事情。 你需要使upload()方法异步(这通常意味着它将采用一个回调参数或返回一个Future ),然后调用它而不阻塞post() (我建议使用@gen.coroutine装饰器并调用慢速操作通过让他们回归的Futures )。 The @asynchronous decorator should be used to mark a metho ...
  • 正如Sushant Khurana所说,你可以“猴子补丁”urllib2。 幸运的是,你不必自己做: 别人为你做了 ! 查看eventlet : http : //eventlet.net/doc/index.html 它基本上实现了自己的socket , urllib2 , asyncore等异步版本。查看其文档和这篇博文 。 我自己从未使用它,但看起来很有前途! As suggested by Sushant Khurana, you could "monkey patch" urllib2. Fort ...
  • write()不会在网络上阻塞(它只是附加到缓冲区),但是你不会放弃任何地方,所以在任何其他任务可以运行之前,整个循环必须运行完成。 我认为问题不在于写入,而是迭代 - “for cursor in cursor”不会产生,所以momoko将整个结果集缓存在内存中,或者在从数据库读取时阻塞。 如果是后者,则需要以非阻塞方式访问游标。 如果是前者,除了将查询分解为更小的块之外,可能没有太多可以做的事情。 (你可以在循环过程中偶尔调用“yield gen.Task(self.flush)”,但这会延长全部数据在 ...
  • 如果你在谈论OpenShift V2(不是使用Kubernetes / Docker的V3),那么你需要使用app.py文件,如下所述: http://blog.dscpl.com.au/2015/08/running-async-web-applications-under.html If you are talking about OpenShift V2 (not V3 which uses Kubernetes/Docker), then you need to use the app.py fil ...

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。