2015-03-24 79 views
0

您的程序應該將「NY」的所有出現次數替換爲「New York」,將所有出現的「NJ」替換爲「New Jersey編寫一個程序,要求用戶輸入地址文件的名稱和輸出文件的名稱

例如,如果你的文件replace.txt包含:

from wikipedia: 
NY-NJ-CT Tri-State Area 
The NY metropolitan area includes the most populous city in the US 
(NY City); counties comprising Long Island and the Mid- and Lower Hudson 
Valley in the state of New York. 

輸出必須是:

from wikipedia: 
New York-New Jersey-CT Tri-State Area 
The New York metropolitan area includes the most populous city in the United 
States (New York City); counties comprising Long Island and the Mid- and 
Lower Hudson Valley in the state of New York. 

我盡力了,這裏是我的程序

filename = input("Please enter a file name: ") 
openfile = open(filename, "r") 
readfile = openfile.read() 


for i in readfile: 
    for string in i.replace("NY", "New York"): 
     Replace = string.replace("NJ", "New Jersey") 

print(Replace) 

問題是它沒有打印出任何東西。 請幫助!

回答

0

只需更換兩個thinkgs,這就夠了:

Replace = readfile.replace("NJ", "New Jersey") 
Replace = Replace.replace("NY", "New York") 

# or 
# Replace = readfile.replace("NJ", "New Jersey").replace("NY", "New York") 

print(Replace) 

你不需要任何這裏循環。 readfile已經包含了輸入文件的全部內容。

要將結果保存在一個新的文件:

with open("outfile.txt",'w') as f: 
    f.write(Replace) 
+0

不適用於新澤西州! – kunjani 2015-03-24 23:46:24

+0

只換NY! – kunjani 2015-03-24 23:46:35

+0

現在有效。你在我編輯安納塞爾時檢查過。 – Marcin 2015-03-24 23:46:48

0

喜歡的東西:

for i in readfile: 
    i = i.replace("NY", "New York") 
    i = i.replace("NJ", "New Jersey") 
    print (i) 

但它並不完全正確,因爲你正在閱讀的整個文件到ReadFile的。按行處理文件通常更好

filename = input("Please enter a file name: ") 
with open(filename, "r") as readfile: 
    for i in readfile: 
     i = i.replace("NY", "New York") 
     i = i.replace("NJ", "New Jersey") 
     print (i) 
相關問題