使用正则表达式将句子拆分成标记(tokens),并去掉所有不必要的标点符号,但保留作为单词一部分的标点符号,可以通过以下步骤实现:
以下是一个示例代码,展示了如何实现这一目标:
import re
def tokenize_sentence(sentence):
# 定义需要去掉的标点符号
punctuation_to_remove = r'[!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~]'
# 使用正则表达式去掉不必要的标点符号
cleaned_sentence = re.sub(punctuation_to_remove, '', sentence)
# 使用正则表达式拆分句子成标记
tokens = re.findall(r'\b\w+\b', cleaned_sentence)
return tokens
# 示例句子
sentence = "Hello, world! This is a test-sentence with e-mail addresses like test@example.com."
# 拆分成标记
tokens = tokenize_sentence(sentence)
print(tokens)
[!"#$%&\'()*+,-./:;<=>?@[\\]^_
{|}~]`来匹配所有不必要的标点符号。re.sub
函数将所有匹配的标点符号替换为空字符串,从而去掉它们。re.findall
函数和正则表达式\b\w+\b
来匹配所有单词边界内的单词,从而将句子拆分成标记。对于示例句子:
sentence = "Hello, world! This is a test-sentence with e-mail addresses like test@example.com."
输出的标记将是:
['Hello', 'world', 'This', 'is', 'a', 'testsentence', 'with', 'email', 'addresses', 'like', 'testexamplecom']
-
)和点(.
)被去掉了,因为它们被认为是不必要的标点符号。如果你希望保留这些符号作为单词的一部分,可以调整正则表达式。例如,保留连字符和点:def tokenize_sentence(sentence):
# 定义需要去掉的标点符号,保留连字符和点
punctuation_to_remove = r'[!"#$%&\'()*+,/:;<=>?@[\\]^_`{|}~]'
# 使用正则表达式去掉不必要的标点符号
cleaned_sentence = re.sub(punctuation_to_remove, '', sentence)
# 使用正则表达式拆分句子成标记
tokens = re.findall(r'\b[\w.-]+\b', cleaned_sentence)
return tokens
# 示例句子
sentence = "Hello, world! This is a test-sentence with e-mail addresses like test@example.com."
# 拆分成标记
tokens = tokenize_sentence(sentence)
print(tokens)
这样,输出的标记将是:
['Hello', 'world', 'This', 'is', 'a', 'test-sentence', 'with', 'e-mail', 'addresses', 'like', 'test@example.com']
通过调整正则表达式,你可以灵活地控制哪些标点符号需要去掉,哪些需要保留。
领取专属 10元无门槛券
手把手带您无忧上云