删除文件tex中的非ASCII字符

2024-09-30 16:38:48 发布

您现在位置:Python中文网/ 问答频道 /正文

Python专家:

我有句话像: "this time air\u00e6\u00e3o was filled\u00e3o" 我希望删除非Ascii unicode字符。 我只需要以下代码和函数:

def removeNonAscii(s): 
    return "".join(filter(lambda x: ord(x)<128, s))          

sentence = "this time air\u00e6\u00e3o was filled\u00e3o"   
sentence = removeNonAscii(sentence)
print(sentence)

然后显示:"this time airo was filledo",删除“\00…”效果很好 但当我把这个句子写进一个文件里,然后读它,然后做成一个循环:

^{pr2}$

它显示"this time air\u00e6\u00e3o was filled\u00a3o" 一点也不管用。这里发生了什么?如果函数有效,则不应该 往那边走。。。。在


Tags: 函数代码timeasciiunicodeairthis字符
1条回答
网友
1楼 · 发布于 2024-09-30 16:38:48

我觉得文件中的文本不是实际的non-ascii字符,而是实际显示字符的utf-8序列,也就是说,它实际上是代码\u00 ,因此当你运行代码时,它读取每一个字符,并看到它们是完全正确的,所以过滤器会离开它们。在

如果是这种情况,请使用以下方法:

import re
def removeNonAscii(s):
    return re.sub(r'\\u\w{4}','',s)

它将删除'\u'的所有实例

示例:

^{pr2}$

在哪里文件.txt有:

^{bq}$

相关问题 更多 >