gpt4 book ai didi

python - 从大型 unicode 文本文件中删除符号

转载 作者:行者123 更新时间:2023-11-30 23:17:56 24 4
gpt4 key购买 nike

我有一个文本文件,其中包含大小约为 2GB 的 Unicode 文本。我尝试使用以下代码删除所有符号

import re
symbols = re.compile(r'[{} &+( )" =!.?.:.. / | » © : >< # « ,] 1 2 3 4 5 6 7 8 9 _ - + ; [ ] %',flags=re.UNICODE)

with open('/home/corpus/All12.txt','a') as t:
with open('/home/corpus/All11.txt', 'r') as n:
data = n.readline()
data = symbols.sub(" ", data)
t.write(data)

用于测试代码的小文件:

:621   

"

:621 "
:621 :1 ;"
_ " :594 :25 4 8 0 :23 "സര്‍ക്കാര്‍ജീവനക്കാരുടെ ശമ്പളം അറിയാന്‍ ഭാര്യമാര്‍ക്ക് അവകാശമുണ്ട്വിവരാവകാശകമ്മീഷന്‍
:621 :4 0 3 0 ;"
_ " :551 :16 :3 "

:12 :70 ;" " " ="" " " ="" " " ="" +


_ " :541 :26 :30 45 5 35 "
=' 'ന്യൂഡല്‍ഹി: സര്‍ക്കാര്‍ജീവനക്കാരായ ഭര്‍ത്താക്കന്മാരുടെ ശമ്പളം

期望输出是ന്യൂഡൽഹിസർക്കാർജീവനക്കാരായഭർത്താക്കന ്മാരുടെശമ്പളം。该代码无法运行。它停止了我的计算机。

不用正则表达式我可以解决这个问题吗?

最佳答案

您需要在方括号 [] 中插入要替换的每个符号,转义一些特殊符号,例如 [] 本身、单引号 '\ 。正则表达式是 r'[-0-9{}&+()"=!.?:/|»©><#«,_+;%\[\]@$*\'\\^~\n\t]'

演示:

>>> st='1234567890-=[]\;,./\'!@#$%^&*()_+{}|":<>?//.,`~ajshgasd'
>>> print re.sub(r'[-0-9{}&+()"=!.?:/|»©><#«,_+;%\[\]@$*\'\\^`~\n\t]','',st)
ajshgasd

存档:

>>> fp=open('file.txt','r')    
>>> for line in fp:
... if line.strip() == '': continue # strip() removes leading and trailing spaces
... print re.sub(r'[-0-9{}&+()"=!.?:/|»©><#«,_+;%\[\]@$*\'\\^`~]','',line).strip(),
...
ന്യൂഡല്‍ഹി സര്‍ക്കാര്‍ജീവനക്കാരായ ഭര്‍ത്താക്കന്മാരുടെ ശമ്പളം

要将输出写入文件,请使用以下代码:

of=open('outfile.txt','w')
fp=open('file.txt','r')
for line in fp:
if line.strip() == '': continue # strip() removes leading and trailing spaces
rline = re.sub(r'[-0-9{}&+()"=!.?:/|»©><#«,_+;%\[\]@$*\'\\^`~]','',line).strip()
if rline == '': continue # skip empty lines
of.write(rline+'\n')

of.close()
fp.close()

关于python - 从大型 unicode 文本文件中删除符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27062615/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com