如何将大量数据的首字母大写?

时间:2017-04-30 15:17:33

标签: python

我是Python新手,差不多20-25天,我已经研究了很多,虽然我找到了一种方法来使用以下python代码来大写(第一个字母),名称和地址数据,我用过'atom editor'用于编写代码,'Powershell'用于检查代码。

原始数据:

john deere
apt. no. 23,
9th floor, sixth avenue,
michael street, new arc,
edmonton, canada.

代码

value = """john deere apt.
         no. 23, 9th floor,
         sixth avenue, michael street,
         new arc,
         edmonton,
         canada.
         """
# Convert to title case.
result = value.title()
print(result)

结果:

John Deere
Apt. No. 23,
9th Floor, Sixth Avenue,
Michael Street, New Arc,
Edmonton, Canada.

现在假设我必须将这些名字的第一个字母大写&在'Note Pad'中的地址和一次只有二十个地址,我该怎么做?如何输入数据?如何将它作为输出返回'Notepad'。如果有人能指导我,我将非常感激。

这是数据在记事本中的显示方式

  1. john deere
    apt. no. 23,
    9th floor, sixth avenue,
    michael street, new arc,
    edmonton, canada.
    
  2. peter simons.
    ..address here.
    .........
    ..........
    
  3. florence nightingale
    ...........
    ...........
    ..........
    
  4. 等等......

3 个答案:

答案 0 :(得分:0)

如果您不想覆盖实际文件的内容,则可以将输出写入新文件。但是,如果使用相同的文件,请说文件名为with open('data.txt', 'w+') as f: data = f.read() data = data.title() f.write(data)

{{1}}

答案 1 :(得分:0)

这应该有用。

f = open("infile.txt", "r") # change this with your file name, open your source file to read
out = open("outfile.txt", "w") # open your output file to write
for line in f: # read from input line by line
    out.write(line.title()) # write to your output line by line

答案 2 :(得分:0)

最简单的方法是使用fileinput模块。它可以非常轻松地处理文件就地,甚至可以选择创建备份文件。

以下是如何使用它来解决您的问题:

import fileinput

filename = 'addresses.txt'
backup = '.bak'  # will create backup file named 'addresses.txt.bak'

with fileinput.input(filename, inplace=True, backup=backup) as file:
    for line in file:
        print(line.title(), end='')  # end='' suppresses extra newline normally added

print('done')

然而,使用字符串.title()方法并不总能正常工作,因为它会执行诸如将"sak's 5th ave"之类的内容转换为"Sak'S 5Th Ave"之类的内容,因为它可以简单地将单词识别为任何一组连续的信件。

这类问题的一个解决方法是使用Python的正则表达式(正则表达式)模块(名为re)来定义自己的自定义单词模式匹配逻辑。

为了说明如何执行此操作,以下代码已修改为使用re和自定义正则表达式模式,以避免前面提到的两个问题:

import re

def titlecase(s):
    return re.sub(r"\b[A-Za-z]+('[A-Za-z]+)?",
                  lambda mo: mo.group(0)[0].upper() + mo.group(0)[1:].lower(),
                  s)

filename = 'addresses.txt'
backup = '.bak'  # will create backup file named 'addresses.txt.bak'

with fileinput.input(filename, inplace=True, backup=backup) as file:
    for line in file:
        print(titlecase(line), end='')  # end='' suppresses extra newline normally added

print('done')