简体   繁体   中英

Write a program that asks the user for the name of file of addresses and a name of an output file

Your program should replace all occurrences of "NY" with "New York," all occurrences of "NJ" with "New Jersey

For example, if your file replace.txt contains:

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.

The output has to be:

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.

I tried my best and here is my program.

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)

The problem is that it is not printing out anything. PLEASE HELP!

Just for replacing the two thinkgs, this is enough:

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)

You dont need any for loops here. readfile already contains full contents of the input file.

To save the results in a new file:

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

Something like:

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

But it's not quite correct, as you are reading the entire file into readfile. It's often better to process the file line by line

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM