如何用单字代替重复字 [英] How to replace repeated words with single word

查看:27
本文介绍了如何用单字代替重复字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串变量response

where where where is it         
I'm going there
where where did you say
sometimes it is where you think
i think its where where you go
its everywhere where you are
i am planning on going where where where i want to

如您所见,"where"这个词经常被重复。我想将字符串"where where"和"where where"(甚至"where")替换为"where"。

但是,我不想将"Everywhere where"替换为"where"。

我知道我可以手动完成此操作,但我希望将代码压缩到尽可能少的几行中。

这是我到目前为止一直在尝试的:

gen temp = regexr(response, " (where)+ where ", " where ") 
replace temp = regexr(response, "^(where)+ where ", "where ")

以下是我运行上述代码后的结果:

where where is it  
I'm going there
where did you say
sometimes it is where you think
i think its where where you go
its everywhere where you are
i am planning on going where where where i want to

相反,我希望最终数据如下所示:

where is it         
I'm going there
where did you say
sometimes it is where you think
i think its where you go
its everywhere where you are
i am planning on going where i want to

我一直使用"(Where)+"来捕获"where"和"where where",但它似乎不起作用。我还将代码分成两个命令,一个以"^(Where)"开头,另一个以"(Where)"开头,以避免捕获"Everywhere"中的"where",但当"where"出现在句子中间时,代码似乎没有捕获"where"。

推荐答案

使用Stata的字符串函数的快速修复如下:

clear

input str50 string1
"where where where is it"        
"I'm going there"
"where where did you say"
"sometimes it is where you think"
"i think its where where you go"
"its everywhere where you are"
"i am planning on going where where where i want to"
end

generate tag1 = !strmatch(string1, "*everywhere where*")

generate tag2 = ( length(string1) - length(subinstr(string1, "where", "", .)) ) / 5

generate string2 = cond(tag1 == 1, stritrim(subinstr(string1, "where", "", tag2-1)), string1)


list string2, separator(0)

     +----------------------------------------+
     |                                string2 |
     |----------------------------------------|
  1. |                            where is it |
  2. |                        I'm going there |
  3. |                      where did you say |
  4. |        sometimes it is where you think |
  5. |               i think its where you go |
  6. |           its everywhere where you are |
  7. | i am planning on going where i want to |
     +----------------------------------------+

这篇关于如何用单字代替重复字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆