2009-08-07 11 views
2

Ruby에서 텍스트 파싱에 도움을 드리고 싶습니다.텍스트에서 URL을 제거하려면 어떻게해야합니까?

감안할 때 :

@BreakingNews : 태풍 모라 꼿이 대만 안타를, 중국은 수천 http://news.bnonews.com/u4z3

내가 일반 텍스트를 반환, 모든 하이퍼 링크를 제거하고 싶습니다를 배기한다.

그것은 신속하고 더러운 방법으로 또는 정교한 방법으로 수행 할 수 있습니다
@BreakingNews: Typhoon Morakot hits Taiwan, China evacuates thousands 

답변

1
foo = "@BreakingNews: Typhoon Morakot hits Taiwan, China evacuates thousands http://news.bnonews.com/u4z3" 
r = foo.gsub(/http:\/\/[\w\.:\/]+/, '') 
puts r 
# @BreakingNews: Typhoon Morakot hits Taiwan, China evacuates thousands 
-1

. 나는 정교한 방법을 보여주고있다 :

require 'rubygems' 
require 'hpricot' # you may need to install this gem 
require 'open-uri' 

## first getting the embeded/framed html file's url 
start_url = 'http://news.bnonews.com/u4z3' 
doc = Hpricot(open(start_url)) 
news_html_url = doc.at('//link[@href]').to_s.match(/(http[^"]+)/) 

## now getting the news text, its in the 3rd <p> tag of the framed html file 
doc2 = Hpricot(open(news_html_url.to_s)) 
news_text = doc2.at('//p[3]').to_plain_text 
puts news_text 

코드가 각 단계에서 무엇을하는지 이해하려고 노력한다. 그리고 미래의 프로젝트에 지식을 적용하십시오. 이 페이지의 도움을 받아 :

http://wiki.github.com/why/hpricot/an-hpricot-showcase

http://code.whytheluckystiff.net/doc/hpricot/

+1

당신이 모든 질문을 읽어 표시되지 않습니다. – hobodave

+0

@hobodave : 다시 시도했는데 이번에는 지난 번 질문에 대한 오해가있었습니다. 나는 나쁜 영어가 관련되어 있다고 생각했고 그는 그 링크에서 텍스트를 얻고 싶다. 그 일에 대해 미안합니다. 그럼 아주 간단한 문제. –

+0

hpricot은 더 이상 권장되지 않습니다. 나는 사실상의 표준이고 지원의 hpricot의 단서 인 Nokogiri를 사용하도록 제안 할 것이다. –

1

이 오래된,하지만 좋은 질문이다.

require 'set' 
require 'uri' 

text = '@BreakingNews: Typhoon Morakot hits Taiwan, China evacuates thousands http://news.bnonews.com/u4z3' 

schemes_regex = /^(?:#{ URI.scheme_list.keys.join('|') })/i 

URI.extract(text).each do |url| 
    text.gsub!(url, '') if (url[schemes_regex]) 
end 

puts text.squeeze(' ') 

그리고 IRB 일이 일어나고 그 결과 출력 있는지 보여주는를 통해 패스 :

irb(main):004:0* text = '@BreakingNews: Typhoon Morakot hits Taiwan, China evacuates thousands http://news.bnonews.com/u4z3' 
=> "@BreakingNews: Typhoon Morakot hits Taiwan, China evacuates thousands http://news.bnonews.com/u4z3" 

: 나는 검색 할 텍스트를 정의

여기에 루비의 내장에있는 URI에 의존 답변입니다 나는 우리가 반응하고자하는 URI 스킴의 정규식을 정의했다. 이는 URI가 검색 단계에서 거짓 긍정을 반환하기 때문에 방어적인 조치입니다.

irb(main):006:0* schemes_regex = /^(?:#{ URI.scheme_list.keys.join('|') })/i 
=> /^(?:FTP|HTTP|HTTPS|LDAP|LDAPS|MAILTO)/i 

URI가 텍스트 찾기 URL을 걷게하십시오. 우리가 텍스트에서 모든 항목을 제거에 반응하고자하는 계획의 경우, 발견 각각에 대해 :

irb(main):008:0* URI.extract(text).each do |url| 
irb(main):009:1* text.gsub!(url, '') if (url[schemes_regex]) 
irb(main):010:1> end 

이 발견 된 URL을 URI.extract입니다. 그것은 후행 : 때문에 실수로 BreakingNews:을보고합니다. 나는 너무 정교한 아니라 생각하지만, 정상적인 사용에 대한 괜찮아 : 결과 텍스트가 무엇인지

=> ["BreakingNews:", "http://news.bnonews.com/u4z3"] 

쇼 :

irb(main):012:0* puts text.squeeze(' ') 
@BreakingNews: Typhoon Morakot hits Taiwan, China evacuates thousands 
관련 문제