2015-03-24 62 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) 
相关问题