Как заменить первое слово строки в Python? - PullRequest
0 голосов
/ 21 мая 2018

Данные моего входного файла выглядят следующим образом.

0,@rodriigoCabrera y tu vaso tu silla y tu baño

1,Mexican rival demands vote recount: The leader of Mexico's leftist Party of the Democratic Revolution, Andres Ma...

0,Queretaro 0 - 3 Morelia Tarjeta amarilla a Carlos Adrián Morales Higuera

Я хочу заменить все 0 в первом столбце на false и 1 на true.

Ответы [ 2 ]

0 голосов
/ 21 мая 2018
newfile = []
with open('input.txt', 'rU') as file:
    lines = file.readlines()
    for line in lines:
        if line[0] == "0":
            line = line.replace("0", "False", 1)
        elif line[0] == "1":
            line = line.replace("1", "True", 1)
        newfile.append(line)

with open('output.txt', 'w') as output:
    print('\n'.join(newfile), file=output)
0 голосов
/ 21 мая 2018

Вы можете сделать это примерно так:

with open('file1', 'rU') as f:
    for line in f:
        # split the line (only once) on a comma
        value, rest = line.split(',', 1)

        # join the line back together, but change the 1/0 to true/false
        print(','.join(('true' if int(value) else 'false', rest)))

Результаты:

false,@rodriigoCabrera y tu vaso tu silla y tu baño    
true,Mexican rival demands vote recount: The leader of Mexico's leftist Party of the Democratic Revolution, Andres Ma...    
false,Queretaro 0 - 3 Morelia Tarjeta amarilla a Carlos Adrián Morales Higuera
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...