简体   繁体   English

尝试不使用正则表达式删除标点符号

[英]Trying to remove punctuation without using regex

I am trying to remove punctuation from an array of words without using regular expression. 我试图从不使用正则表达式的单词数组中删除标点符号。 In below eg, 在下面,例如

str = ["He,llo!"]

I want: 我想要:

result # => ["Hello"]

I tried: 我试过了:

alpha_num="abcdefghijklmnopqrstuvwxyz0123456789"
result= str.map do |punc|  
  punc.chars {|ch|alpha_num.include?(ch)}  
end 
p result

But it returns ["He,llo!"] without any change. 但是它返回["He,llo!"]没有任何更改。 Can't figure out where the problem is. 无法找出问题所在。

include? block returns true/false , try use select function to filter illegal characters. 块返回true/false ,请尝试使用select函数过滤非法字符。

result = str.map {|txt| txt.chars.select {|c| alpha_num.include?(c.downcase)}}
            .map {|chars| chars.join('')}

p result
str=["He,llo!"]
alpha_num="abcdefghijklmnopqrstuvwxyz0123456789"

Program 程序

v=[]<<str.map do |x|
  x.chars.map do |c|
    alpha_num.chars.map.include?(c.downcase) ? c : nil
  end
end.flatten.compact.join

pv 光伏

Output 产量

["Hello"]
exclusions = ((32..126).map(&:chr) - [*'a'..'z', *'A'..'Z', *'0'..'9']).join
  #=> " !\"\#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"

arr = ['He,llo!', 'What Ho!']    

arr.map { |word| word.delete(exclusions) }
  #=> ["Hello", "WhatHo"]

If you could use a regular expression and truly only wanted to remove punctuation, you could write the following. 如果您可以使用正则表达式并且真正只想删除标点符号,则可以编写以下内容。

arr.map { |word| word.gsub(/[[:punct:]]/, '') }
  #=> ["Hello", "WhatHo"]

See String#delete . 参见String#delete Note that arr is not modified. 请注意, arr不会被修改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM