【问题标题】:How to replace all multiple instances of different symbols in a string如何替换字符串中不同符号的所有多个实例
【发布时间】:2022-12-10 23:15:38
【问题描述】:

现在我正在进行我的第一个 NLP 项目,使用 python 和 BERT 进行嵌入。

我有一个文本语料库,但在没有任何预处理的情况下,BERT 分词器会将几乎所有的单词和符号作为分词。

我有一个 4k 重复“!”的情况在其中一篇文章中,所以我无法制作张量(最多只需要 512 个标记)。

我知道如何使用 re 替换具体符号的多个实例:

import re

text = 'I hate you!!!!!!!!!!!!!'

fixed_text = re.sub('!+', '!', text)

所以,这是微不足道的。

我想做的是将任何符号的所有双实例和更多实例替换为双实例。

例如,这个字符串:

亚伦想买一个 hoooooooouse :DDDD

应转化为:

亚伦想买房子:DD

有什么方法可以替换所有此类重复,而无需分别为每个符号使用 re.sub 吗?

我知道我可以轻松找到所有这些多个字母:

re.findall((\w)\1+, txt)

所以对于所有非字母字符:

re.findall((\W)\1+,txt)

但我无法立即替换它们,因为 re.sub 不会将此 '\1\1' 作为参数。

【问题讨论】:

标签: python python-re


【解决方案1】:

要替换字符串中不同符号的所有多个实例,您可以在循环中使用 replace() 方法将每个符号替换为所需的值。

例如,假设您有一个名为 text 的字符串,其中包含符号 @、$ 和 # 的多个实例,并且您想要将它们替换为相应的词“at”、“dollar”和“number”。您可以使用以下代码:

text = "The #1 stock to buy is @Tesla for $1000"
# Define a dictionary of symbols and their replacements
replacements = {
    "@": "at",
    "$": "dollar",
    "#": "number"
}

# Loop through the dictionary and replace each symbol with its corresponding value
for symbol, replacement in replacements.items():
    text = text.replace(symbol, replacement)

print(text)  # Output: The number 1 stock to buy is at Tesla for dollar 1000

在此示例中,替换字典是使用符号及其对应的替换项定义的。然后使用 for 循环遍历字典并对每个符号的文本字符串调用 replace() 方法,将其替换为相应的值。然后将生成的字符串打印到屏幕上。

或者,您可以使用正则表达式在单个步骤中匹配和替换不同符号的多个实例,如下所示:

import re

text = "The #1 stock to buy is @Tesla for $1000"

# Define a regular expression pattern that matches the symbols
pattern = re.compile(r"[@#$]")

# Use the regular expression to replace the symbols with their corresponding values
text = pattern.sub(r"at", r"dollar", r"number", text)

print(text)  # Output: The number 1 stock to buy is at Tesla for dollar 1000

在此示例中,正则表达式模式是使用 re.compile() 方法定义的。该模式匹配任何符号 @、$ 或 #。然后使用 sub() 方法将匹配的符号替换为其对应的值。然后将生成的字符串打印到屏幕上。

总体而言,replace() 方法或正则表达式可用于替换字符串中不同符号的所有多个实例。这些方法提供了一种高效灵活的方式来执行此类字符串操作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-24
    • 1970-01-01
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-04
    • 2012-11-14
    相关资源
    最近更新 更多