【问题标题】:Replace all characters except for alphanumerics from all languages替换所有语言中除字母数字以外的所有字符
【发布时间】:2019-07-04 08:44:40
【问题描述】:

如何使用 Python 将特殊字母/字符保存在文本文件中?

输入文本文件:

abcÃ/cdéf@-www

我想去掉符号,但保留字母和特殊字母,符号表示~!@#$%^*()_+{}<>:"|等等。在我尝试运行我的代码之后,这是我得到的:

输出文本文件:

abc  cd f  www

符号已被删除并替换为我想要的空格,但特殊字母已被删除并替换为我不想要的空格。有什么办法可以去掉符号,只保留特殊字母?

预期的输出文本文件:

abcà cdéf  www

这是我的代码:

string = open('abc.txt', encoding='utf-8').read()
new_str = re.sub('[^a-zA-Z0-9\n\.]', ' ', string)
open('abc.txt', 'w', encoding='utf-8').write(new_str)

【问题讨论】:

  • new_str = ''.join([char fro char in string if char not in "~!@#$%^*()_+{}<>:\"|"]) 可能不是最好的解决方案,但仍然是一个可行的解决方案
  • @xiidref 这是一个解决方案,还有一个isalpha 方法可以在这里工作:"àbc".isalpha() # >> True
  • 您是否尝试删除\n\。在你的代码中?
  • @JuliusLimson 是的,我试过了

标签: python regex


【解决方案1】:

将第二行替换为:

new_str = re.sub('[^\w\s.,;]', ' ', string)

【讨论】:

  • 您还添加了他想要替换的@。你的答案是最好的,但你打破了它,包括串很多东西。
  • @Marek。我的手指发生了不好的事情。现在再次编辑。
  • 我曾尝试替换此代码,但出现此错误:``` UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc3 in position 3: invalid continuation byte ```跨度>
  • 工作 pretty well 除了希伯来语(添加一些额外的空格)。
  • @JānisŠ。如何验证我的文本文件是非 utf8 编码的?如果是非utf8编码怎么解决?
【解决方案2】:

您可以指定仅删除特殊字符/标点符号

puncts = re.escape(string.punctuation)
print re.sub(r'['+ puncts +']', '', your_string)

【讨论】:

  • 你应该避免使用+来格式化字符串:realpython.com/python-string-formatting/…
  • 我曾尝试替换此代码,但出现此错误:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc3 in position 3: invalid continuation byte
  • 在解释器或 python 脚本中检查你的编码
【解决方案3】:

你可以试试这个:

import re
string = open('abc.txt', encoding='utf-8').read()
new_str = re.sub('[/~!@#$%^*()_+{}<>:"|-]', ' ', string) # put your characters to replace here
open('abc.txt', 'w', encoding='utf-8').write(new_str)

输出是:

abcà cdéf  www

【讨论】:

  • 我曾尝试替换此代码,但出现此错误:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc3 in position 3: invalid continuation byte
猜你喜欢
  • 2013-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-26
  • 1970-01-01
  • 2017-09-01
  • 2013-01-19
相关资源
最近更新 更多