各単語の最初の文字を取り、スペースと句読点を残します


8

文字列のグループの文字列内の各単語を、スペースまたは句読点で区切られた1文字に縮小します。

I'm a little teapot,  short and stout. Here is my handle, here is my spout. When I get all steamed up - hear me shout!   Tip me over and pour me out. 

なる

I' a l t, s a s. H i m h, h i m s. W I g a s u - h m s! T m o a p m o. 

編集-複数のスペースがある場合は、1つのスペースのみを保持します。句読点はすべて保存する必要があります。アポストロフィがありませんでした。はい、これはコードゴルフです:-)。


1
単語間に複数のスペースを入れることはできますか?それらを保存する必要がありますか?
デニス

8
また、どの文字が句読点として正確にカウントされますか?
デニス

1
句読点(+など)以外の数字やその他の文字に必要な動作は何ですか
grovesNL

1
1つの単語に複数の句読点が含まれることはありますか?のようなものO'Leary-Clarence-DeVoisになりO'--ますか?
hmatt1 2015年

8
いつでも解答を受け入れることができますが、チャレンジをクローズする前に時間(日)を空けることをお勧めします。
edc65

回答:


5

CJam、13バイト

r{(\'A,f&Sr}h

一般的な句読文字のみを考慮でき、出力に末尾のスペースを含めることができれば機能します。(デニスに感謝します。)

この質問はもっと明確にする必要があります...

CJam、17 16バイト

r{(\eu_elf&Sr}h&

オンラインでお試しください

説明

r          e# Read one word from input.
{          e# While it is not EOF:
    (\     e# Extract the first character.
    eu     e# Convert the rest to uppercase.
    _el    e# And lowercase.
    f&     e# Delete characters in the first string if not in the second string.
    S      e# Append a space.
    r      e# Read the next word.
}h
&          e# Discard the last space by intersecting with empty string.

リンクを追加してテストできますか?私は携帯しています。
Cthanatos、2015年

@Cthanatosが追加されました。
jimmy23013 2015年

1
rこの作品のようにも、EOFに空の文字列をプッシュ:r{(\eu_elf&Sr}h;
デニス

1
@Dennisそのようなコードを何度も見たと思いますが、それでも覚えていません...ありがとう。しかし、;その意味はありません。
jimmy23013

1
必要に応じて、でそれを取り除くこともできます&。また、句読点として正確に数えられるものによっては'@,、のより短い代替となりeu_elます。
デニス

4

Pyth、14バイト

jdm+hd-rtd0Gcz

オンラインで試す:デモ

説明:

                 implicit: z = input string
            cz   split z by spaces
  m              map each word d to:
    hd              first letter of d
   +                +
       rtd0         (lowercase of d[1:]
      -    G         but remove all chars of "abc...xyz")
jd               join resulting list by spaces and print

これは重複するハイフンですか?
Cthanatos

@Cthanatosは今すぐ動作するはずです。
ジャクベ2015年

@grovesNLあなたは通常の執筆で出くわす可能性のある文、つまり、文の中の数字が問題となるか、出てくるかもしれない本、ニュース記事を考えることができますか?
Cthanatos

@Cthanatos:本やニュース記事で数字が使用されるケースはたくさんあります。「200人を超える回答者...」「50エーカーの敷地です...」「約20リットルを保持できます...
grovesNL

Touché...良い点。
Cthanatos

2

Python 3.4、 94 92 82 77バイト

print(*[w[0]+''.join(c[c.isalpha():]for c in w[1:])for w in input().split()])

コードゴルフは初めてですが、試してみようと思いました。これは勝者ではありませんが、楽しかったです。

これは文字列を分割し、各単語の最初の文字と残りの単語の句読点を取ります。

* FryAmTheEggman、DLoscによる変更で編集


Pythonのスター付き引数を使用していくつかのバイトを保存できます。条件を反転させると1バイトを節約できるようです(ただし、疑わしいゴルフのように見えます)。ここに私が得たものがあります:print(*[w[0]+''.join([c for c in w[1:]if 1-c.isalpha()])for w in input().split()])
FryAmTheEggman

@FryAmTheEggmanああ、ありがとう!スター付きの引数の受け渡しを忘れていました。
Robotato、2015年

2
内包表記を囲む角括弧は不要ですjoin。引数として裸のジェネレータを使用できます。また、「ifalphaでない」ロジックを実行する文字列スライスの方法を次に示しますc[c.isalpha():]for c in w。77バイトに減らす必要があります。:^)
DLosc

@DLoscその文字列スライスのトリックは巧妙です、ありがとう!覚えておく必要があります。
Robotato、2015年


1

sed(39文字)

いくつかの正規表現:

sed 's+\<\(.\)[A-Za-z]*+\1+g;s+  *+ +g'

2
通常、インタープリターの名前と、コードまたはデータをインタープリターに正しく渡すためにシェルが必要とする追加の構文はカウントしません。実際のSedコードは32文字のみです。
manatwork

1

Lua-126文字

Luaはコードゴルフ言語ではありませんが、試してみました。

a=''for b in string.gmatch( c, '%S+%s?' )do d=(b:match('%w')or''):sub(1,1)e=b:match('[^%s%w]')or''a=a..d..e..' 'end print( a )

これはc文字列であると想定しています。

ここでは、読みやすくするためにクリーンアップされています。

local string = [[I'm a little teapot,  short and stout. Here is my handle, here is my 
spout. When I get all steamed up - hear me shout!   Tip me over and pour me out.]]

local final = ''
for word in string.gmatch( string, '%S+%s?' ) do 
    local first = ( word:match( '%w' ) or '' ):sub( 1, 1 )
    local second = word:match( '[^%s%w]' ) or ''
    final = final .. first .. second .. ' '
end
print( final )

ここでテストすることができます(コピーして貼り付けます。最初に行う必要もありc = "I'm a little ...ます)。何らかの理由で、Luaのオンラインデモでは、変数を入力できませんio.read...



1

Javascript(ES672 68バイト

f=x=>x.split(/\s+/).map(x=>x.replace(/^(.)|[a-z]/gi,'$1')).join(' ')
<input id="input" value="I'm a little teapot,  short and stout. Here is my handle, here is my spout. When I get all steamed up - hear me shout!   Tip me over and pour me out. " />
<button onclick="output.innerHTML=f(input.value)">Run</button>
<br /><pre id="output"></pre>

コメント:

f=x=>
    x.split(/\s+/). // split input string by 1 or more spaces
    map(x=> // map function to resulting array
        x.replace(/^(.)|[a-z]/gi, '$1') // capture group to get the first character
                                        // replace all other letters with empty string
    ).
    join(' ') // join array with single spaces

1

C99 - 170の 169バイト

main(_,a)char**a;{for(char*b=a[1],*c=b,*e,*d;*c++=*b;){for(e=b;*++b&&*b-32;);for(*b=0,d=strpbrk(e,"!',-."),d&&d-e?*c++=*d:0;b[1]==32;++b);++b;*c++=32;*c=0;}puts(a[1]);}

未ゴルフ:

main(int argc, char**a) {
    char*b=a[1],*c=b,*e,*d;
    while(*c++=*b){
        for(e=b;*++b&&*b-32;); //scan for first space or end of word
        *b=0; //mark end of word
        for(;b[1]==32;++b); //skip following spaces
        d=strpbrk(e,"!',-."); //find punctuation
        if(d&&d-e) //append punctuation if any, and it's not the word itself
            *c++=*d;
        *c++=32; //append space
        b++;
    }
    *c=0; //mark end of line
    puts(a[1]);
}

使用法:

gcc -std=c99 test.c -o test
./test "I'm a little teapot,  short and stout. Here is my handle, here is my spout. When I get all steamed up - hear me shout!   Tip me over and pour me out."

出力:

I' a l t, s a s. H i m h, h i m s. W I g a s u - h m s! T m o a p m o.

1

Java 8、87バイト

s->{for(String x:s.split(" +"))System.out.print(x.replaceAll("^(.)|[a-z]+","$1")+" ");}

説明:

ここで試してください。

s->{                                  // Method with String parameter and no return-type
  for(String x:s.split(" +"))         //  Split the input on one or multiple spaces
                                      //  And loop over the substrings
    System.out.print(                 //   Print:
      x.replaceAll("^(.)|[a-z]+","$1")//    Regex to get the first letter + all non-letters
      +" ");                          //    + a space delimiter
                                      //  End of loop (implicit / single-line body)
}                                     // End of method

正規表現の説明:

x.replaceAll("^(.)|[a-z]+","$1")
x.replaceAll("           ","  ") # Replace the match of String1 with String2, in String `x`
             "           "       # Regex to match:
              ^(.)               #  The first character of String `x`
                  |[a-z]+        #  Or any one or multiple lowercase letters
                           "  "  # Replace with:
                            $1   #  The match of the capture group (the first character)

したがって、最初の文字を除いて、基本的に文字列のすべての小文字を削除します。



0

R、46 45バイト

cat(gsub("^\\w\\W*\\K\\w*","",scan(,""),T,T))

これにより、STDINから行が読み取られ、STDOUTに出力されます。正規表現を使用して、最初の文字の後にすべての文字を削除し、その後に句読点を追加します。

非ゴルフ+説明:

# Read a string from STDIN and convert it to a character vector,
# splitting at spaces

input <- scan(what = "")

# Replace stuff with nothing using a regex.
# ^ start position anchor
# \w single "word" character
# \W* any amount of non-word (i.e. punctuation) characters
# \K move the match position forward
# \w* any number of word characters

replaced <- gsub("^\\w\\W*\\K\\w*", "", input, ignore.case = TRUE, perl = TRUE)

# Print the vector elements to STDOUT, separated by a space

cat(replaced, sep = " ")

例:

> cat(gsub("^\\w\\W*\\K\\w*","",scan(,""),T,T))
1: I'm a little teapot,  short and stout. Here is my handle, here is my spout. When I get all steamed up - hear me shout!   Tip me over and pour me out. 

I' a l t, s a s. H i m h, h i m s. W I g a s u - h m s! T m o a p m o.


0

VBA(エクセル)、141の 133バイト

VBAイミディエイトウィンドウ、[A1]を入力文字列として使用。

z=" "&[A1]:for a=2 to len(z):c=mid(z,a,1):[A2]=[A2]&IIF(mid(z,a-1,1)=" ",c,IIF(asc(lcase(c))>96 and asc(lcase(c))<123,"",c)):next:?[TRIM(A2)]

z=" "&[a1]:for a=2 to len(z):c=mid(z,a,1):e=asc(lcase(c)):[a2]=[a2]&iif(mid(z,a-1,1)=" ",c,IIF((e>96)*(e<123),"",c)):next:?[TRIM(A2)]

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.