Ruby:从字符串中提取单词 [英] Ruby: Extracting Words From String

查看:90
本文介绍了Ruby:从字符串中提取单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从字符串中解析单词并将它们放入数组中.我已经尝试过以下事情:

I'm trying to parse words out of a string and put them into an array. I've tried the following thing:

@string1 = "oriented design, decomposition, encapsulation, and testing. Uses "
puts @string1.scan(/\s([^\,\.\s]*)/)

这似乎可以解决问题,但是有点不稳定(例如,我应该包含更多特殊字符).有没有更好的办法可以做到这一点呢?

It seems to do the trick, but it's a bit shaky (I should include more special characters for example). Is there a better way to do so in ruby?

可选:我有一个CS课程描述.我打算从中提取所有单词,并将它们放置在字符串数组中,从生成的数组中删除英语中最常见的单词,然后将其余单词用作标记,用户可以使用它们搜索cs课程.

Optional: I have a cs course description. I intend to extract all the words out of it and place them in a string array, remove the most common word in the English language from the array produced, and then use the rest of the words as tags that users can use to search for cs courses.

推荐答案

split命令.

   words = @string1.split(/\W+/)

将基于正则表达式将字符串拆分为一个数组. \ W表示任何非单词"字符,"+"表示组合多个定界符.

will split the string into an array based on a regular expression. \W means any "non-word" character and the "+" means to combine multiple delimiters.

这篇关于Ruby:从字符串中提取单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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