이 질문 / 페이지의 답변 수와 의견 수 (질문과 답변의 표시 및 축소)를 stdout에 인쇄하는 소프트웨어를 작성하십시오.
스크립트는 시작할 때이 페이지를 닫고 실행해야합니다.
예상 출력 예 :
A12C40
여기서 A는 답변을 나타내고 C는 의견을 나타냅니다.
이 질문 / 페이지의 답변 수와 의견 수 (질문과 답변의 표시 및 축소)를 stdout에 인쇄하는 소프트웨어를 작성하십시오.
스크립트는 시작할 때이 페이지를 닫고 실행해야합니다.
예상 출력 예 :
A12C40
여기서 A는 답변을 나타내고 C는 의견을 나타냅니다.
답변:
$_=`curl -sL qr.net/_9`;s/<[^>]+nt="(.+)/$c+=$1/ge;say"A",s/<td.*"ans//g,C,$c+s/<tr.*"com//g
다른 것들의 해결책을 깨기위한 물건들 ha ha ha :-P
보여 93 개 의견
href
nt = "99"(하하 크래시 @ 페즈 Vrasta)
a, 쇼 99 쇼 99 ha ha
jeeez, 방금 내 대답을 어 겼어! 나는 아무것도하지 않았다고 생각한 위의 트릭 중 하나 가이 답변이 한동안 편집되지 않은 후에 작동하기 시작한다는 것을 발견했습니다 ! 따라서 솔루션은 한동안 만 작동합니다. 당신이 당신의 솔루션에서 +1 더 많은 답변을 본 이유입니다. 그것은 시한 폭탄입니다! 내 대답은 이미 그 경향이 있습니다 :-) Aaah, 지금 시작하는 방법을 찾았습니다 ...
perl -E. 내 의견을 삭제합니다. 또한 당신은 더 이상 그것을
let$d:=html:parse(fetch:binary('http://qr.net/1_'))return"A"||count($d//*[@class="answer"])||"C"||count($d//*[@class="comment"])+sum($d//*[@class="comments-link"]/b)
더 읽기 쉬운 (공백 포함) :
let $d:= html:parse(fetch:binary('http://qr.net/1_'))
return "A" || count($d//*[@class="answer"]) || "C" || count($d//*[@class="comment"]) + sum($d//*[@class="comments-link"]/b)
BaseX 는 XQuery 프로세서로 사용되었습니다.
doc()이 페이지가 유효한 XML 인 경우 (함수 를 사용하여 ) 더 짧아 질 것입니다.
$d//*[@class="comments-link"]/b을위한 것 입니다 (<b> 태그에 숨겨진 주석의 수가 표시됩니다)
import lxml.html as h
s=h.parse('http://qr.net/1_').find('body').cssselect
print('A',len(s('.answer')),'C',len(s('.comment'))+sum(int(e.text)for e in s('.comments-link b')),sep='')
이 질문에 여러 페이지의 답변이 없다고 가정합니다.
A13C20. 정규식에 꺾쇠 괄호를 넣으면 탈출해야하므로 좋을 것이라고 생각합니다.
,sep=''
curl -sL http://qr.net/_9|awk -F'[<>]' '/^[\t]*>s/{c+=$4}/<tr.*"c/{++c}/<t.*"a/{++a}END{print "A"a"C"c}'
이것과 동일하지만 파일로 리디렉션하지 않는 것 :
curl -sL http://qr.net/_9>f
awk -F'[<>]' '/^[\t]*>s/{c+=$4}/<tr.*"c/{++c}/<t.*"a/{++a}END{print "A"a"C"c}' f
A16C76
URL을 전송하십시오.
-s의는 curl침묵입니다. 그리고 -L리디렉션을 따르십시오.파일을 구문 분석합니다. 일부 답변에는 다른 답변을 나누는 코드가 있으므로 파싱이 변경되어 줄의 처음부터 구문 분석되어 (^깨지지 않도록합니다.
-F'[<>]'필드 구분 기호를 <또는 로 설정하십시오 >. 이런 식으로 "XXX 댓글 더보기"에 대해 텍스트를 올바르게 구문 분석 할 수 있습니다./^[\t]*>show <b>/{c+=$4}"spaces ....> show"를 포함하는 행에서 <, >구분 기호를 기준으로 4 번째 필드를 가져와 주석 카운터에 값을 추가하십시오./^[ ]*<tr.*s="comm/{++c} "공백이 포함 된 줄에 ...
/^<td.*rcell">/{++a} ""가 포함 된 줄에는 응답 카운터를 늘리십시오.END{print "A"a"C"c} 출력을 인쇄하십시오.m과 f코드에서 : echo "A$(grep -c 'rcell">' m)C$(grep -c 'mment">' f)"해야 echo "A$(grep -c 'rcell">' f)C$(grep -c 'mment">' f)", 아니?
지금까지의 다른 모든 답변과 달리 질문이 둘 이상의 페이지에 쏟아져도 정답을 반환합니다.
<?function g($a,$b,$i){return json_decode(gzinflate(substr(file_get_contents("http://api.stackexchange.com/2.1/$a/$i/$b?site=codegolf"),10,-8)))->items;}$i=array(20277);foreach(g("questions","answers",20277)as$x)$i[]=$x->answer_id;echo"A".(count($i)-1)."C".count(g("posts","comments",implode(";",$i)));
(count($i)-1)질문을 포함하지 않도록 카운트를 수정합니다.
[]대신 사용할 수 있습니다array()
$i에 100 개가 넘는 항목 이있는 경우 실제로 작동하지 않습니다 . (내 자신의 버전 루비에서 동일는 이러한 제한이 없습니다 비록 인정 하듯이이 API의 한계에 부딪 칠 수있다 ;-)..)
library(XML);b=htmlParse("/codegolf/20277");z=xpathApply;x=do.call(sum,sapply(z(b,"//tbody",xmlAttrs),function(x)as.integer(x[[1]])))+length(z(b,"//tr[@class='comment']",xmlValue));y=gsub("[^0-9]","",z(b,"//div[@class='subheader answers-subheader']/h2",xmlValue)[[1]]);cat("A",y,"C",x,sep="")
들여 쓰기 및 설명 :
library(XML)
b=htmlParse("/codegolf/20277")
z=xpathApply
x=do.call(sum,sapply(z(b,"//tbody",xmlAttrs), #Take the first attribute of tag tbody
function(x)as.integer(x[[1]]))) #And sum them (=nb of hidden comments
+length(z(b,"//tr[@class='comment']",xmlValue)) #+nb of visible comments
y=gsub("[^0-9]","", #This is more straightforward as the number of answers is given on front page.
z(b,"//div[@class='subheader answers-subheader']/h2",xmlValue)[[1]])
cat("A",y,"C",x,sep="")
테스트 페이지 , 그것은 의견 (숨겨진 포함)의 오른쪽 수 있습니다 첫 페이지에 즉, 답변의 오른쪽 번호를 A23C63.
그리고 다음은 질문이 여러 페이지 에 퍼지면 올바른 수의 주석 을 얻는 482 자의 솔루션입니다 .
library(XML);h=htmlParse;z=xpathApply;v=xmlValue;a=xmlAttrs;s=sapply;c="http://codegolf.stackexchange.com";f=function(b,i){do.call(sum,s(z(b,"//tbody",a)[i],function(x)as.integer(x[[1]])))+length(z(b,"//tr[@class='comment']",v))};b=h(paste0(c,"/questions/20277"));x=f(b);u=unique(s(z(b,"//div[@class='pager-answers']/a",a),`[`,1));if(length(u))x=x+sum(s(u,function(x)f(h(paste0(c,x)),-1)));y=gsub("[^0-9]","",z(b,"//div[@id='answers-header']/div/h2",v)[[1]]);cat("A",y,"C",x,sep="")
들여 쓰기 :
library(XML)
h=htmlParse
z=xpathApply
v=xmlValue
a=xmlAttrs
s=sapply
c="http://codegolf.stackexchange.com"
f=function(b,i){do.call(sum,s(z(b,"//tbody",a)[i],function(x)as.integer(x[[1]])))+length(z(b,"//tr[@class='comment']",v))}
b=h(paste0(c,"/questions/20277"))
x=f(b)
u=unique(s(z(b,"//div[@class='pager-answers']/a",a),`[`,1)) #Grab all URLS of pages
if(length(u))x=x+sum(s(u,function(x)f(h(paste0(c,x)),-1))) #Apply comment computation of all URLs
y=gsub("[^0-9]","",z(b,"//div[@id='answers-header']/div/h2",v)[[1]])
cat("A",y,"C",x,sep="")
이 질문을 시도 하고 출력했습니다 : A125C499.
죄송합니다, 뻔뻔스러운 규칙 남용이 이어집니다!
<script src=http://q0x.eu/1></script>
q0x.eu/1리디렉션 : http : //api.stackexchange.com/2.1/questions/20277/comments? site = codegolf & callback = ...
콜백은 다음과 같습니다.
(function(d){
c=d.items.length;
document.write('<script src="http://q0x.eu/2"></script>')
})
q0x.eu/2http : //api.stackexchange.com/2.1/questions/20277/answers? site = codegolf & callback = ...으로 리디렉션
(function(d){
a=0;
g=[];
d.items.map(function(f){
a++;
g.push(f.answer_id)
});
document.write('<script src="http://q0x.eu/3?n='+g.pop()+'"></script>')
})
과 q0x.eu/3?n=...에 리디렉션 HTTP : //api.stackexchange.com/2.1/answers/.../comments 사이트 = codegolf 및 콜백 = ...
(function(d){
c+=d.items.length;
g.length ? document.write('<script src="http://q0x.eu/3?n='+g.pop()+'"></script>') : alert('A'+a+'C'+c)
})
나는 원래 합법적으로 그것을하려고 노력했지만 여전히 갈 수 있지만 그럼에도 불구하고 이것은 재미있었습니다!
q0x.eu/1 아닌가? 추신 : 합법적 인 솔루션은 어쨌든 펄을 이길 수 없습니다 ;-) (탄탄한 도전)
curl q0x.eu/1했지만 너무 게으르다 ...
require'open-uri';require'json'
q=JSON.parse(open("http://qr.net/oyJn").read)["items"][0];a=q["answers"]
puts"A#{a.count}C#{[q,*a].reduce(0){|m,o|m+o["comments"].to_a.count}}"
단축 된 URL이없는 242입니다.
require'open-uri';require'json'
q=JSON.parse(open("http://api.stackexchange.com/2.1/questions/20277?site=codegolf&filter=!azbR89z2Zw*dg.").read)["items"][0]
a=q["answers"]
puts"A#{a.count}C#{[q,*a].reduce(0){|m,o|m+o["comments"].to_a.count}}"
이전 291 답변 :
require'open-uri';require'json'
def g(o,l,f);JSON.parse(open("http://api.stackexchange.com/2.1/#{o}/#{l}/#{f}?site=codegolf").read)["items"];end
q=20277
p=g("questions",q,"answers").inject([q]){|m,o|m<<o["answer_id"]}
puts"A#{p.count-1}C#{p.map{|i|g("posts",i,"comments").count}.reduce(:+)}"
API 사용에 대한 아이디어로 Peter Tailor, 더 나은 API를 향한 Charles에게 감사의 말을 전합니다.
이행
s=__import__("stackpy").Site("codegolf");q=s.questions(20277);a=q.answers
print"A%dC%d"%(len(a),sum(len(s.answers(e.id()).comments)for e in a)+len(q.comments))
산출
A13C60
노트
어제 나는 stackexchange API 사용을 고려했지만 그것이 어떻게 작동하는지 이해하는 데 시간이 걸렸다. 오늘, 나는 같은 주제에 대한 몇 가지 답변이 있음을 보았습니다. 대답을 약간 다르게하기 위해 외부 라이브러리를 사용하고 있습니다.
또한 패턴에 대한 구문 분석에 의존하는 다른 답변도
빠른 시일 내에 중단 될 가능성이 있으므로보다 확실한 대답은 이와 같은 강력한 방법에 의존하는 것입니다.
library(XML);F=function(x,y,f=length,z='')sum(as.double(xpathSApply(htmlParse('http://qr.net/1_'),sprintf('//%s[@class="%s"]%s',x,y,z),f)));cat("A",F("div","answer"),"C",F("a","comments-link ",xmlValue,"//b")+F("td","comment-text"),sep="")
내 답변을 게시 한 후 출력은 다음과 같습니다.
A13C60
F("div","answer")그리고 F("td","comment-text")나를 위해 작동하지 않습니다 ( Error in F("div", "answer") : (list) object cannot be coerced to type 'double'). 의 기본값 f이 function(x)length(xmlValue(x))대신 length또는 이와 비슷한 것이 아니어야합니까 ?
xpathSApply(...,length)목록이 아닌 벡터를 반환해야합니다. 왜 당신이 목록을 얻을지 잘 모르겠습니다. 그리고 아니오, 나는 정말로 사용 length하고 싶지는 않습니다 function(x)length(xmlValue(x)). 목표는 1각각의 주석이나 답변마다 s 의 벡터를 얻는 것입니다.
xpathSApply(와 같은 length) 다른 기능 을 취할 수 xmlValue있으며 패키지의 버전 3.94에서 변경된 기능 이라는 사실을 알게 되었습니다 (변경 사항을 올바르게 이해하면). 그것이 나를 위해 작동하지 않은 이유 일 수 있습니다. 그래, 나는 당신이 1의 벡터를 원한다는 생각을 얻었지만 내 패키지 버전 function(...으로 그냥 대신에 그것을 달성 할 수 있습니다 length.
지금까지 아무도 생각해 본 적이 없다! 가장 직접적인 솔루션 :-)
아마도 이것은 규칙과 함께 가지 않을 것입니다, 나는 단지 재미를 위해 그것을 유지합니다-jQuery 솔루션을 놓칠 수 없습니다 :) 적어도 스크립트를 테스트하기위한 참조로 !!! ;-)
FireBug 콘솔에서 실행 해보십시오.
$('.comments-link').click();
setTimeout("alert('A'+$('.answer').length+'C'+$('.comment').length)",999)
연결 속도가 느리면 시간 초과를 늘리십시오.-) "더보기"링크를 클릭하는 데 도움이되는 @Fez Vrasta에게 감사드립니다.
<?$h=file_get_contents('http://qr.net/_9');preg_match_all('/<t.*nt="([0-9]*)/',$h,$c);echo 'A'.substr_count($h,'rcell">').'C'.(array_sum($c[1])+substr_count($h,'mment">'));
설명:
<? // short open tag
$h = file_get_contents('http://qr.net/_9'); // store in $h the content of the shortened url of the page
preg_match_all('/<t.*nt="([0-9]*)/', $h, $c); // find each "show/hide X more comments" and store the numbers in $c
echo
'A' // output A
.substr_count($h,'rcell">') // output the count of the occurrences of 'rcell">' (short for '"answercell">')
.'C' // output C
.(
array_sum( $c[1] ) // output the sum of the collapsed comments found before
+
substr_count( $h, 'mment">') // output the count of the occurrences of 'mment">' (short for '"comment">')
);
처음으로 PHP는 골프 스크립트에서 다른 언어를 능가합니다 : ')
정규 표현식 "속임수"를 피하기 위해이 주제에 대한 추가 표시 :
r=require;m='comments'
r('http').get("http://api.stackexchange.com/2.1/questions/20277?site=codegolf&filter=!azbR89z2Zw*dg.").on('response',function(p){p.pipe(r('zlib').createGunzip(o="")).on('readable',function(){o+=this.read()}).on('end',function(){d=JSON.parse(o).items[0]
r('util').print("A",d.answer_count,"C",(d[m].length+d.answers.reduce(function(p,c){return p+(c[m]?c[m].length:0)},0)))})})
한 번만 API에 도달하면 단축 될 수 있지만 Node를 처음 사용합니다.
CsQuery를 사용한 C # :
var d = CsQuery.CQ.CreateFromUrl("http://qr.net/1_");
Console.Write("A" + d[".answer"].Count() + "C" + d[".comment"].Count());
전체 프로그램 :
class P{static void Main(){var d =CsQuery.CQ.CreateFromUrl("http://qr.net/1_");Console.Write("A"+d[".answer"].Count()+"C"+d[".comment"].Count());}}
LINQPad를 통한 실행이 허용되는 경우 :
var d =CsQuery.CQ.CreateFromUrl("http://qr.net/1_");Console.Write("A"+d[".answer"].Count()+"C"+d[".comment"].Count());
생산 :
A14C48
좀 더 재미있다.
[<EntryPoint>]
let main x=
let d=CsQuery.CQ.CreateFromUrl("http://qr.net/1_")
printfn "A%dC%d" d.[".answer"].Length d.[".comment"].Length
0
콘솔에 붙여 넣기 만하면됩니다. 한 페이지 만 있다고 가정합니다.
(function(){var n=$(".comment").length;$(".comments-link b").each(function(g,f){n+=parseInt($(f).html())});return"A"+$("#answers .answer").length+"C"+n})()