string - 找到单词时的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
解决方案
一个小技巧是,"th"
作为一个单词的前后都会有一个空格,除非它出现在字符串的开头或结尾。例外并不是真正的挑战,因为
gen wanted = strpos(" " + strings + " ", " th ") > 0
在他们周围工作。否则,有一组丰富的正则表达式函数可供使用。
上面的示例标记了不执行您想要的操作的代码压缩为一行,
gen th_pos = strpos(strings, "th") > 0
更直接的答案是您不必更换任何东西。你只需要让 Stata 告诉你如果你这样做会发生什么:
gen WANTED = strings != subinword(strings, "th", "", .)
如果删除子字符串(如果存在)会更改字符串,则它必须已经存在。
推荐阅读
- angular - 使用角度保护 Laravel 中的路线
- python - 由于 node-gyp 无法安装节点模块
- python-3.x - python3希腊字母未正确显示
- python - 如何解密最初使用 Fernet 加密的不同服务上的值?
- python - 在 3D 数组中查找最大值时间
- python - 如何动态循环值以过滤熊猫数据框?
- oracle - 如何在 Oracle 中将 UTF-16 符号代码转换为 nvarchar2?
- r - R:新变量,其值来自另一个变量,基于第三个变量中的最小值,按 ID 分组
- ruby - cron 作业在 shell 脚本中的 ruby 问题
- php - 将 Contact form 7 变量传递到屏幕