如何删除标点符号但保留否定词?

4
假设我有以下句子:

s = c("I don't want to remove punctuation for negations. Instead, I want to remove only general punctuation. For example, keep I wouldn't like it but remove Inter's fan or Man city's fan.")

我希望能够获得以下结果:

"I don't want to remove punctuation for negations Instead I want to remove only general punctuation For example keep I wouldn't like it but remove Inter fan or Man city fan."

如果我简单地使用以下代码,那么我会删除否定中的两个's'和一个撇号。


  s %>%  str_replace_all("['']s\\b|[^[:alnum:][:blank:]@_]"," ")

 "I don t want to remove punctuation for negations  Instead  I want to remove only general punctuation           For example  keep I wouldn t like it but remove Inter  fan or Man city  fan "


总之,我需要一个能够去除一般标点符号的代码,包括 "'s",但要保留原始格式的否定词。
有人可以帮助我吗?
谢谢!

否定总是"'t",也许只需使用固定匹配删除"'s" - zx8754
问题在于我仍然需要清除一般的标点符号。无论我使用哪种清理策略,都会删除 "'t" - Rollo99
1
然后分两步进行,删除所有标点符号,但保留单引号,然后使用固定匹配删除 "'s"。 - zx8754
为什么句号“.”在末尾没有被移除? - zx8754
2个回答

2
您可以使用“向前查看”(?!t)来测试[:punct:]后面是否跟随一个t,以此来判断文本中的内容。
gsub("[[:punct:]](?!t)\\w?", "", s, perl=TRUE)
#[1] "I don't want to remove punctuation for negations Instead I want to remove only general punctuation For example keep I wouldn't like it but remove Inter fan or Man city fan"

如果您想更加严格一些,可以额外测试是否在前面没有n,使用的是(?<!n)
gsub("(?<!n)[[:punct:]](?!t)\\w?", "", s, perl=TRUE)

如果需要将其限制为仅限于't,可以采取以下措施(感谢@chris-ruehlemann)

gsub("(?!'t)[[:punct:]]\\w?", "", s, perl=TRUE)

或者删除所有标点符号, 但不包括 ' 或者 's:

gsub("[^'[:^punct:]]|'s", "", s, perl = TRUE)

使用前瞻来实现相同的功能:

gsub("(?!')[[:punct:]]|'s", "", s, perl = TRUE)

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接