python 中如何将文本中的所有单词首字母转换为大写,其余为小写

 

1、

[root@PC1 test2]# ls
a.txt  test.py
[root@PC1 test2]# cat a.txt       ## 测试数据
dsfs JHDSF
ADFD dfesr
fKHJ FJfdf
[root@PC1 test2]# cat test.py     ## 转换程序
#!/usr/bin/python

in_file = open("a.txt", "r")
out_file = open("result.txt", "w")

lines = in_file.readlines()

for i in lines:
    temp = i.split()
    for j in range(0,len(temp)):
        temp[j] = temp[j].capitalize()
    out_file.write(" ".join(temp))
    out_file.write("\n")

in_file.close()
out_file.close()
[root@PC1 test2]# python test.py       ## 执行程序
[root@PC1 test2]# ls
a.txt  result.txt  test.py
[root@PC1 test2]# cat result.txt       ## 转换结果
Dsfs Jhdsf
Adfd Dfesr
Fkhj Fjfdf

 

posted @ 2022-06-01 23:13  小鲨鱼2018  阅读(566)  评论(0编辑  收藏  举报