gpt4 book ai didi

ruby - 如何在 ruby 中使用匹配?

转载 作者:数据小太阳 更新时间:2023-10-29 08:36:39 24 4
gpt4 key购买 nike

我试图从文本中获取大写单词。我如何为此使用 .match() ?示例

text = "Pediatric stroke (PS) is a relatively rare disease, having an estimated incidence of 2.5–13/100,000/year [1–4], but remains one of the most common causes of death in childhood, with a mortality rate of 0.6/100,000 dead/year [5, 6]"

我需要这样的东西:

r = /[A-Z]/
puts r.match(text)

我从未使用过 match,我需要一种获取所有大写单词(首字母缩写词)的方法。

最佳答案

如果你只想要首字母缩略词,你可以使用类似的东西:

text = "Pediatric stroke (PS) is a relatively rare disease, having an estimated incidence of 2.5–13/100,000/year [1–4], but remains one of the most common causes of death in childhood, with a mortality rate of 0.6/100,000 dead/year [5, 6]"

text.scan(/\b[A-Z]+\b/)
# => ["PS"]

匹配整个单词很重要,这正是 \b 的用武之地,因为它标记了单词边界。

问题是当您的文本包含单个独立的大写字母时:

text = "Pediatric stroke (PS) I U.S.A"

text.scan(/\b[A-Z]+\b/)
# => ["PS", "I", "U", "S", "A"]

到那时,我们需要对正在搜索的文本内容有更多的了解和预知。问题是,单字母首字母缩略词有效吗?如果没有,那么稍作修改将有所帮助:

text.scan(/\b[A-Z]{2,}\b/)
# => ["PS"]

{2,}the Regexp documentation 中解释,因此请阅读以获取更多信息。


i only want acronym type " (ACRONYM) ", in this case PS

通过您的描述很难说出您想要什么。首字母缩略词定义为:

An acronym is an abbreviation used as a word which is formed from the initial components in a phrase or a word. Usually these components are individual letters (as in NATO or laser) or parts of words or names (as in Benelux).

根据 Wikipedia .根据该定义,小写、全部大写和混合大小写都是有效的。

如果,你的意思是你只想在括号内全部大写,那么你可以很容易地修改正则表达式来满足这一点,但是你会在你可能遇到的其他首字母缩写词上失败,要么丢失你应该想要的首字母缩写词,要么通过捕获其他你应该忽略的。

text = "(PS) (CT/CAT scan)"
text.scan(/\([A-Z]+\)/) # => ["(PS)"]

text.scan(/\([A-Z]+\)/).map{ |s| s[1..-2] } # => ["PS"]

text.scan(/\(([A-Z]+)\)/) # => [["PS"]]
text.scan(/\(([A-Z]+)\)/).flatten # => ["PS"]

获取文本的方式多种多样,但这只会在您查看“List of medical abbreviations”和“Medical Acronyms / Abbreviations”时打开一个新的蠕虫 jar 头。

通常我会有一张我会接受的表格,使用一个简单的模式来捕获任何看起来像我想要的东西,检查它是否在表格中然后保留它或拒绝它。如何做到这一点是你自己想出来的,因为这是一个完全不同的问题,不属于这个问题。

关于ruby - 如何在 ruby 中使用匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34138979/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com