如何替换Python中行的第一个单词?

2024-09-25 18:25:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我的输入文件数据是这样的。你知道吗

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

我想用false替换第一列中的所有0,用true替换1。你知道吗


Tags: 文件ofthe数据leadervotebatu
2条回答
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)

你可以这样做:

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

相关问题 更多 >