【问题标题】:Removing consecutive symbols/characters found after a word for multiple tokens删除多个标记的单词后发现的连续符号/字符
【发布时间】:2021-11-24 16:20:00
【问题描述】:

在不同的单词/标记之后重复出现一个奇怪的图标。示例如下:

到目前为止,我已使用替换命令将其删除,但是如果对每个单词单独执行,这可能会变得乏味。

图中的符号表示为\x9d.当前python代码如下:

import re
 text = ['unstable',
 'people\x9d.',
 'pattern',
 'real',
 'thought',
 'fearful',
 'represent',
 'contrarians\x9d',
 'greedy',
 'interesting',
 'behaviour',
 'opposite']
  text = [k.replace('basket\x9d.', 'basket') for k in text]
  text = [k.replace('people\x9d.', 'people') for k in text]
  text = [k.replace('portfolios.\x9d', 'portfolios') for k in text]

我曾尝试使用 re.sub 检测模式,但未能成功实现。

text = [re.sub('\x9d', '', str(k)) for k in text] 

此代码将完全删除该单词。

【问题讨论】:

  • 那么,[k.replace('\x9d.', '') for k in text] 呢?还是您想在contrarians 之后保留它?您是否有要删除特殊符号的单词列表或过滤列表?
  • 它有效 text =['unstable', 'people\x9d.', 'pattern', 'real', 'thought', 'fearful', 'represent', 'contrarians\x9d.' , '贪婪', '有趣', '行为', '相反'] text = [k.replace('\x9d.', '') for k in text]

标签: python string replace


【解决方案1】:

在这里,您需要删除两个字符的序列,\x9d.

您可以在列表推导中使用简单的str.replace

text = [k.replace('\x9d.', '') for k in text]

Python demo

import re
text = ['unstable','people\x9d.','pattern','real','thought','fearful','represent','contrarians\x9d','greedy','interesting','behaviour','opposite']
text = [k.replace('\x9d.', '') for k in text]
print(text)
# => ['unstable', 'people', 'pattern', 'real', 'thought', 'fearful', 'represent', 'contrarians\x9d', 'greedy', 'interesting', 'behaviour', 'opposite']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-10
    • 2019-11-29
    • 2019-01-18
    • 1970-01-01
    • 1970-01-01
    • 2020-04-18
    相关资源
    最近更新 更多