编写一个程序,询问用户地址文件的名称和输出文件的名称

时间:2015-03-24 23:41:10

标签: python text

您的计划应该取代所有出现的" NY"与"纽约,"所有出现的" NJ"与"新泽西州

例如,如果您的文件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)

问题是它没有打印出任何东西。 请帮助!

2 个答案:

答案 0 :(得分:0)

只是为了取代两个想法,这就足够了:

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)

这里你不需要任何for循环。 readfile已包含输入文件的完整内容。

将结果保存在新文件中:

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

答案 1 :(得分: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)