How can I capitalize the first letter of each word?

亡梦爱人 提交于 2019-12-30 11:30:11

问题


I need a script in any language to capitalize the first letter of every word in a file.

Thanks for all the answers.

Stackoverflow rocks!


回答1:


In Python, open('file.txt').read().title() should suffice.




回答2:


Using the non-standard (Gnu extension) sed utility from the command line:

sed -i '' -r 's/\b(.)/\U\1/g' file.txt

Get rid of the "-i" if you don't want it to modify the file in-place.

note that you should not use this in portable scripts




回答3:


C#:

string foo = "bar baz";
foo = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(foo);
//foo = Bar Baz



回答4:


From the shell, using ruby, this works assuming your input file is called FILENAME, and it should preserve all existing file formatting - it doesn't collapse the spacing as some other solutions might:

cat FILENAME | ruby -n -e 'puts $_.gsub(/^[a-z]|\s+[a-z]/) { |a| a.upcase }'



回答5:


Scala:

scala> "hello world" split(" ") map(_.capitalize) mkString(" ")
res0: String = Hello World

or well, given that the input should be a file:

import scala.io.Source
Source.fromFile("filename").getLines.map(_ split(" ") map(_.capitalize) mkString(" "))



回答6:


You can do it with Ruby too, using the command line format in a terminal:

cat FILENAME | ruby -n -e 'puts gsub(/\b\w/, &:upcase)'

Or:

ruby -e 'puts File.read("FILENAME").gsub(/\b\w/, &:upcase)'



回答7:


A simple perl script that does this: (via http://www.go4expert.com/forums/showthread.php?t=2138)

sub ucwords {
  $str = shift;
  $str = lc($str);
  $str =~ s/\b(\w)/\u$1/g;
  return $str;
}

while (<STDIN>) {
    print ucwords $_;
}

Then you call it with

perl ucfile.pl < srcfile.txt > outfile.txt



回答8:


bash:

$ X=(hello world)
$ echo ${X[@]^}
Hello World



回答9:


This is done in PHP.

$string = "I need a script in any language to capitalize the first letter of every word in a file."
$cap = ucwords($string);



回答10:


VB.Net:

Dim sr As System.IO.StreamReader = New System.IO.StreamReader("c:\lowercase.txt")
Dim str As String = sr.ReadToEnd()
sr.Close()
str = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(str)
Dim sw As System.IO.StreamWriter = New System.IO.StreamWriter("c:\TitleCase.txt")
sw.Write(str)
sw.Close()



回答11:


php uses ucwords($string) or ucwords('all of this will start with capitals') to do the trick. so you can just open up a file and get the data and then use this function:

<?php 
$file = "test.txt"; 
$data = fopen($file, 'r');
$allData = fread($data, filesize($file));
fclose($fh);
echo ucwords($allData);
?>

Edit, my code got cut off. Sorry.




回答12:


Here's another Ruby solution, using Ruby's nice little one-line scripting helpers (automatic reading of input files etc.)

ruby -ni~ -e "puts $_.gsub(/\b\w+\b/) { |word| word.capitalize }" foo.txt

(Assuming your text is stored in a file named foo.txt.)

Best used with Ruby 1.9 and its awesome multi-language support if your text contains non-ASCII characters.




回答13:


ruby:

irb> foo = ""; "foo bar".split.each { |x| foo += x.capitalize + " " }
=> ["foo", "bar"]

irb> foo
=> "Foo Bar "



回答14:


In ruby:

str.gsub(/^[a-z]|\s+[a-z]/) { |a| a.upcase }

hrm, actually this is nicer:

str.each(' ') {|word| puts word.capitalize}



回答15:


perl:

$ perl -e '$foo = "foo bar"; $foo =~ s/\b(\w)/uc($1)/ge; print $foo;'

Foo Bar




回答16:


Although it was mentioned in the comments, nobody ever posted the awk approach to this problem:

$ cat output.txt
this is my first sentence. and this is the second sentence. that one is the third.
$
$ awk '{for (i=0;i<=NF;i++) {sub(".", substr(toupper($i), 1,1) , $i)}} {print}' output.txt 
This Is My First Sentence. And This Is The Second Sentence. That One Is The Third.

Explanation

We loop through fields and capitalize the first letter of each word. If field separator was not a space, we could define it with -F "\t", -F "_" or whatever.




回答17:


zsh solution

#!/bin/zsh
mystring="vb.net lOOKS very unsexy"
echo "${(C)mystring}"
Vb.Net Looks Very Unsexy

Note it does CAP after every non alpha character, see VB.Net .




回答18:


Very basic version for AMOS Basic on the Amiga — only treats spaces as word separators though. I'm sure there is a better way using PEEK and POKE, but my memory is rather rusty with anything beyond 15 years.

FILE$=Fsel$("*.txt")
Open In 1,FILE$
Input #1,STR$
STR$=Lower$(STR$)
L=Len($STR)
LAST$=" "
NEW$=""
For I=0 to L-1
  CUR$=MID$(STR$,I,1)
  If LAST$=" "
    NEW$=NEW$+Upper$(CUR$)
  Else
    NEW$=NEW$+$CUR$
  Endif
  LAST$=$CUR$
Next
Close 1
Print NEW$

I miss good old AMOS, a great language to learn with... pretty ugly though, heh.




回答19:


Another solution with awk, pretending to be simpler instead of being shorter ;)

$ cat > file
  thanks for all the fish
  ^D
$ awk 'function tocapital(str) {
           if(length(str) > 1)
               return toupper(substr(str, 1, 1)) substr(str,2)
           else
               return toupper(str)
       }

       {
           for (i=1;i<=NF;i++) 
               printf("%s%s", tocapital($i), OFS);
           printf ORS
       }
      ' < file
  Thanks For All The Fish



回答20:


If using pipes and Python:

$ echo "HELLO WORLD" | python3 -c "import sys; print(sys.stdin.read().title())"
Hello World

For example:

$ lorem | python3 -c "import sys; print(sys.stdin.read().title())"
Officia Est Omnis Quia. Nihil Et Voluptatem Dolor Blanditiis Sit Harum. Dolore Minima Suscipit Quaerat. Soluta Autem Explicabo Saepe. Recusandae Molestias Et Et Est Impedit Consequuntur. Voluptatum Architecto Enim Nostrum Ut Corrupti Nobis.

You can also use things like strip() to remove spaces, or capitalize():

$ echo "  This iS mY USER ${USER}   " | python3 -c "import sys; print(sys.stdin.read().strip().lower().capitalize())"
This is my user jenkins


来源:https://stackoverflow.com/questions/880597/how-can-i-capitalize-the-first-letter-of-each-word

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!