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

2024-04-25 19:29: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.

现在假设如果我必须将“记事本”中的这些名称和地址的第一个字母大写,一次大写20个,那么我如何才能做到这一点,如何输入数据,以及如何将数据作为输出返回到“记事本”中。如果有人能指导我,我将不胜感激。你知道吗

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

  1. 你知道吗

    john deere
    apt. no. 23,
    9th floor, sixth avenue,
    michael street, new arc,
    edmonton, canada.
    
  2. 你知道吗

    peter simons.
    ..address here.
    .........
    ..........
    
  3. 你知道吗

    florence nightingale
    ...........
    ...........
    ..........
    

诸如此类。。。。你知道吗


Tags: 数据no代码streetnewaptjohn大写
3条回答

如果不想覆盖实际文件的内容,则可以将输出写入新文件。但是,使用同一个文件时,假设文件名是data.txt。你知道吗

with open('data.txt', 'w+') as f:
    data = f.read()
    data = data.title()
    f.write(data)

最简单的方法是使用^{}模块。它使文件的就地处理变得非常容易,甚至可以选择创建备份文件。你知道吗

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

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')

然而,使用string .title()方法并不总是能正常工作,因为它会将"sak's 5th ave"之类的内容转换成"Sak'S 5Th Ave",因为它只将单词识别为任何一组连续的字母。你知道吗

解决这类问题的一种方法是使用Python的regex(正则表达式)模块^{},来定义您自己的自定义单词模式匹配逻辑。你知道吗

为了说明如何做到这一点,前面的代码被修改为使用re和一个自定义regex模式,可以避免前面提到的两种问题:

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')

这应该管用。你知道吗

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

相关问题 更多 >