首页 > 解决方案 > 找到单词时的Stata标志,而不是strpos

问题描述

我有一些带有字符串的数据,我想在找到单词时进行标记。一个单词将被定义为在字符串的开头、结尾或分隔一个空格。strpos只要字符串存在就会找到,但我正在寻找类似于subinword. Stata 是否有办法使用的功能subinword而不必替换它,而是标记这个词?

clear 
input id str50 strings
1 "the thin th man"
2  "this old then"
3 "th to moon"
4 "moon blank th"
end

gen th_pos = 0
replace th = 1 if strpos(strings, "th") >0

上面的代码将标记每个观察,因为它们都包含“th”,但我想要的输出是:

ID      strings          th_sub
1   "the thin th man"      1
2   "this old then"        0
3   "th to moon"           1
4   "moon blank th"        1

标签: stringstata

解决方案


一个小技巧是,"th"作为一个单词的前后都会有一个空格,除非它出现在字符串的开头或结尾。例外并不是真正的挑战,因为

gen wanted = strpos(" " + strings + " ", " th ") > 0  

在他们周围工作。否则,有一组丰富的正则表达式函数可供使用。

上面的示例标记了不执行您想要的操作的代码压缩为一行,

gen th_pos = strpos(strings, "th") > 0

更直接的答案是您不必更换任何东西。你只需要让 Stata 告诉你如果你这样做会发生什么:

gen WANTED = strings != subinword(strings, "th", "", .)

如果删除子字符串(如果存在)会更改字符串,则它必须已经存在。


推荐阅读