繁体   English   中英

如何从字符串中删除选定的字符?

[英]How to remove selected characters from a string?

我一直在尝试学习如何删除随机给定字符串上的特殊字符。 一个随机给定的字符串可能是这样的:

uh\n  haha - yes 'nope' \t tuben\xa01337

我已经使用了 regex 和string.translate来尝试对我有用的方法:

import re

random_string = "uh\n  haha - yes 'nope' \t tuben\xa01337"

print(re.sub(r"/[' \n \t\r]|(\xa0)/g", '', random_string))
print("-------")
print(random_string.translate(str.maketrans({c: "" for c in "\n \xa0\t\r"})))

返回的 output :

uh
  haha - yes 'nope'      tuben 1337
-------
uhhaha-yes'nope'tuben1337

问题是它不能按我的意愿工作,因为我希望 output 是:

uh haha - yes nope tuben 1337

我想知道我怎么能做到这一点?

  • \n\t\xa0 或任何类似的应替换为一个空格
  • ' 和 " 应该替换为没有空格,只需删除 ' 和 "
  • 双空格或更多应替换为总共只有一个空格。 这意味着如果文本中有两个或多个空格,则应将其替换为一个。
  • 任何特殊字符也应删除

您可以使用

import re
random_string = "uh\n  haha - yes 'nope' \t tuben\xa01337"
random_string = re.sub(r"\s+", " ", random_string).strip().replace('"', '').replace("'", '')
print(random_string)

请参阅Python 演示

备注

  • re.sub(r"\s+", " ", random_string) - 将一个或多个空白字符的任何块收缩为单个常规空格字符
  • .strip() - 删除前导/尾随空格
  • .replace('"', '').replace("'", '') - 删除"'字符。
 /[' \n \t\r]|(\xa0)/g

这是 sed 或 Vim 等工具使用的语法,而不是 Python 的re模块。

等价的将是

print(re.sub(r"[' \n \t\r]|(\xa0)", '', random_string))

哪个打印

uhhaha-yesnopetuben1337

这并不遥远,但您还删除了所有空格。

如果你不删除空格,

print(re.sub(r"['\n\t\r]|(\xa0)", '', random_string))

你得到

uh  haha - yes nope  tuben1337

其中有太多的空间。

一种解决方案是使用正则表达式(匹配您想要保留的字符的运行)和re.findall来获取单词列表,然后您可以重新加入:

result = re.findall(r"[^' \n\t\r\xa0]+", random_string)
print(' '.join(result))

哪个打印

uh haha - yes nope tuben 1337

这个正则表达式可以解决问题:

>>> print(re.sub(" +", ' ', re.sub(r'''/|[^\w\s]|\n|\t|\r|(\xa0)/g''', '', random_string)))
uh haha yes nope tuben 1337

外部的re.sub匹配多个空格并将其替换为一个空格。

内部re.sub几乎与您正在使用的相同,我只是发现将它们全部作为|的选择更具可读性 .

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM