Ruby 如何将标签从tweet中分离出来?
从字符串中删除哈希标记,然后将哈希标记字连接到另一个由逗号分隔的字符串中的好方法是什么:Ruby 如何将标签从tweet中分离出来?,ruby,Ruby,从字符串中删除哈希标记,然后将哈希标记字连接到另一个由逗号分隔的字符串中的好方法是什么: 'Some interesting tweet #hash #tags' 结果将是: 'Some interesting tweet' 以及: 这有一个开始为空的散列数组 然后,它根据空格拆分哈希标记 然后它寻找一个散列标签并抓取单词的其余部分 然后将其存储到数组中 array_of_hashetags = [] array_of_words = [] str = "Some interesting
'Some interesting tweet #hash #tags'
结果将是:
'Some interesting tweet'
以及:
这有一个开始为空的散列数组 然后,它根据空格拆分哈希标记 然后它寻找一个散列标签并抓取单词的其余部分 然后将其存储到数组中
array_of_hashetags = []
array_of_words = []
str = "Some interesting tweet #hash #tags"
str.split.each do |x|
if /\#\w+/ =~ x
array_of_hashetags << x.gsub(/\#/, "")
else
array_of_words << x
end
end
array\u of_hashetags=[]
数组\u of_words=[]
str=“一些有趣的tweet#hash#标签”
str.split.each do|x|
如果/\\w+/=~x
数组\u hashetags另一种方法是使用scan
然后删除hash标签:
tweet = 'Some interesting tweet #hash #tags'
tags = tweet.scan(/#\w+/).uniq
tweet = tweet.gsub(/(?:#{ Regexp.union(tags).source })\b/, '').strip.squeeze(' ') # => "Some interesting tweet"
tags.join(',').tr('#', '') # => "hash,tags"
对它的剖析表明:
tweet.scan(/#\w+/)
返回一个数组[“#hash”,“#tags”]
uniq
将删除任何重复的标记
Regexp.union(tags)
返回(?-mix:\\散列\标记)
Regexp.union(tags).source
返回\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\。我们不希望在开始时使用模式标志,因此使用source
可以解决这个问题
/(?:{Regexp.union(tags.source})b/
返回正则表达式/(?:\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\标记)\b/
- 是将一个或多个字符转换为另一个字符或去除字符的极快方法
最终的正则表达式并不是可以生成的最优化的正则表达式。我实际上会编写代码来生成:
/#(?:hash|tags)\b/
但如何做到这一点,留给你作为练习。而且,对于短字符串来说,就速度而言,它不会有太大的差别。对于一些#hash interest tweet#标记
,预期的结果是什么?为什么要用字符串来做这件事?Twitter API包含预解析的哈希标记,包括它们在推文中的位置。@DaveNewton推文完全可能不是从推文中提取的。他不想要“#哈希,#标记”
。他想要“hash,tags”
@theTinMan,+1所有推文都是“短”字符串:)谢谢Regexp.union
。我不知道,是的,我知道。区别在于长字符串,当它们有数千个字符长时,即使这样,也会很小<当您需要搜索多个数组元素时,code>Regexp.union
是一种很好的方法。我一直都在用它,你可以找到我在这里用过的很多例子。
tweet = 'Some interesting tweet #hash #tags'
tags = tweet.scan(/#\w+/).uniq
tweet = tweet.gsub(/(?:#{ Regexp.union(tags).source })\b/, '').strip.squeeze(' ') # => "Some interesting tweet"
tags.join(',').tr('#', '') # => "hash,tags"
/#(?:hash|tags)\b/