您的位置:首页 > 编程语言 > Python开发

使用python处理文件,将文件中的每一行首字母大写

2017-07-13 00:00 483 查看
摘要: 持续学习中,做个简单记录……

一、背景:

有个文本文件,内容不多,想将每行数据的首字母大写。

$ cat test
map
filter
flatMap
mapPartitions
mapPartitionsWithIndex
sample
union
intersection
distinct
groupByKey
reduceByKey
aggregateByKey
sortByKey
join
cogroup
cartesian
pipe
coalesce
repartition
repartitionAndSortWithinPartitions

二、处理办法

1.使用python处理,目前想到两种处理办法:

$ cat dlw.py

#!/usr/bin/python
# -*- coding: UTF-8 -*-

class Capfile:

def __init__(self, f):
self.f = f
# 方法1,使用python函数capitalize()来处理,这个处理的结果数据会变成首字母大写,其它字母都小写了
def capfile1(self):
of = open(file1)
wf = open(file2, 'w')
for i in of.readlines():
d = i.capitalize()
print d
wf.write(d)
of.close()
wf.close()
# 方法2,使用upper对第一个字母进行大写转换,然后拼接剩下的字母
def capfile2(self):
of = open(file1)
wf = open(file3, 'w')
for i in of.readlines():
d = i[0].upper() + i[1:]
print d
wf.write(d)
of.close()
wf.close()

file1 = "/home/spark/test"
file2 = "/home/spark/test1"
file3 = "/home/spark/test2"
f = ""
inst = Capfile(f)
inst.capfile1()
inst.capfile2()

2.使用软件处理

使用Notepad++,列编辑模式选中首行

大写:ctrl+shift+u

小写:ctrl+u
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: