【问题标题】:How to remove every special character except for the hyphen and the apostrophe inside and between words words?如何删除除单词内部和单词之间的连字符和撇号之外的每个特殊字符?
【发布时间】:2020-08-19 14:27:36
【问题描述】:

作为一个例子,我已经设法打破了这个句子 “那是——美味的井字游戏。或者——不是?”成这样的单词数组: words['That's', 'a-', 'tasty', 'tic-tac.','Or', '-not?'].

现在我必须删除我不需要的每个特殊字符并得到这个:words['That's', 'a', 'tasty', 'tic-tac','Or', 'not']

我当前的实际代码如下所示:

pattern = re.compile('[\W_]+')

for x in range(0, file_text.__len__()):

for y in range(0, file_text[x].__len__()):

    word_list.append(pattern.sub('', file_text[x][y]))

我有一个完整的文本,我首先将其变成行和单词,然后变成单词

【问题讨论】:

  • 请尝试为此类问题提供示例输入(几句话,您已经有一些)和预期输出(使您的目标尽可能清晰)
  • 等等,你的意思是连字符单撇号吗?如果是,请使用re.sub(r'\b([-'])\b|[\W_]', r'\1', text)
  • 我编辑了帖子,因为我的意图不够清楚
  • 您说您有一个名为words 的列表,其中包含这些字词。就用那个吧。

标签: python regex


【解决方案1】:

你可以使用

r"\b([-'])\b|[\W_]"

参见regex demo(该演示稍作修改,因此[\W_] 无法匹配换行符,因为演示站点的输入是单个多行字符串)。

正则表达式详细信息

  • \b([-'])\b - 一个-',用字字符(字母、数字或下划线)括起来(注意,如果你使用(?<=[^\W\d_])([-'])(?=[^\W\d_]),你可能只需要排除用字母括起来的匹配这些符号)
  • | - 或
  • [\W_] - 除字母或数字以外的任何字符。

Python demo

import re
words = ["That's", 'a-', 'tasty', 'tic-tac.','Or', '-not?']
rx = re.compile(r"\b([-'])\b|[\W_]")
print( [rx.sub(r'\1', x) for x in words] )
# => ["That's", 'a', 'tasty', 'tic-tac', 'Or', 'not']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-01
    • 2013-12-26
    • 1970-01-01
    相关资源
    最近更新 更多