gpt4 book ai didi

r - 如何在 R 中的字符串中添加缺少的右括号?

转载 作者:行者123 更新时间:2023-12-02 01:32:39 24 4
gpt4 key购买 nike

我想向具有左括号但缺少右括号的字符串添加右括号。例如,我想将“狗在公园散步(ABC)”修改为“狗在公园散步(ABC)”。

我发现了类似的问题和解决方案,但它是用 Python 编写的( How to add a missing closing parenthesis to a string in Python? )。我尝试修改R中使用的代码但无济于事。有人可以帮我解决这个问题吗?

我尝试修改原始的 python 解决方案,因为 R 无法识别“r”,并且“\”已被“\\”替换,但此解决方案无法正常工作,并且不会捕获前面的字符串我想添加的括号:

text = "The dog walked (ABC in the park"
str_replace_all(text, '\\([A-Z]+(?!\\))\\b', '\\)')
text

有效的Python解决方案如下:

text = "The dog walked (ABC in the park"
text = re.sub(r'(\([A-Z]+(?!\))\b)', r"\1)", text)
print(text)

最佳答案

试试这个

stringr::str_replace_all(text, '\\([A-Z]+(?!\\))\\b', '\\0\\)') 
  • 输出
"The dog walked (ABC) in the park"

关于r - 如何在 R 中的字符串中添加缺少的右括号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72950868/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com