2017-04-30 38 views
-1

我對Python很新,只有20-25天,我已經研究了很多,雖然我已經找到一種方法來利用(首字母),名稱和地址數據通過使用下面的Python代碼,我用'原子編輯器'來編寫代碼,'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 
    ........... 
    ........... 
    .......... 
    

等等等等....

+0

請標出最佳答案 –

回答

0

如果你不希望覆蓋實際文件的內容,那麼你可以寫輸出到一個新文件。然而,使用相同的文件,假設文件名是data.txt

with open('data.txt', 'w+') as f: 
    data = f.read() 
    data = data.title() 
    f.write(data) 
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 
0

最簡單的方法是使用fileinput模塊。它可以非常簡單地處理文件in-place,甚至可以選擇創建備份文件。

以下是如何用它來解決你的問題:因爲它承認

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