2015-03-24 3 views
0

Ваша программа должна заменить все вхождения «Нью-Йорк» на «Нью-Йорк», все вхождения «Нью-Джерси» в «Нью-Джерси»Напишите программу, которая запрашивает у пользователя имя файла адресов и имя выходного файла

Например, если ваш файл 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

не работает для NJ! – kunjani

+0

ТОЛЬКО заменяет NY! – kunjani

+0

Теперь он работает. Вы проверяли, когда я добавляю edditing anwser. – Marcin

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) 
Смежные вопросы