【问题标题】:Stata flag when word found, not strpos找到单词时的Stata标志,而不是strpos
【发布时间】:2021-03-07 17:35:20
【问题描述】:

我有一些带字符串的数据,我想在找到单词时进行标记。单词将被定义为在字符串的开头、结尾或分隔一个空格。 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

【问题讨论】:

    标签: string stata


    【解决方案1】:

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

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

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

    上面的例子标记了不做你想做的事情的代码压缩到一行,

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

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

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

    如果删除子字符串(如果存在)会更改字符串,则它一定存在。

    【讨论】:

      【解决方案2】:

      正则表达式对于这种类型的练习很有用,单词边界允许您搜索由\b 指示的整个单词,如"\bword\b"

      gen wanted = ustrregexm(strings, "\bth\b")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-06
        • 2012-12-19
        • 2016-03-29
        • 1970-01-01
        • 2011-08-12
        相关资源
        最近更新 更多