我的输入文件数据是这样的。
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。
答案 0 :(得分:4)
你可以这样做:
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
答案 1 :(得分:0)
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)