【问题标题】:How to replace first word of line in Python?如何替换Python中的第一个单词?
【发布时间】:2018-10-30 16:23:49
【问题描述】:

我的输入文件数据是这样的。

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。

【问题讨论】:

  • 你试过什么?你在哪里卡住了 - 似乎是一个简单的 split() join() 问题。或者,如果您使用的是csv,那么row[0] = <mapped-value>
  • 对不起,我是新手,所以如果你能建议我代码示例会很棒
  • 编写一个新文件然后将其重命名为原始名称要容易得多。

标签: python csv parsing


【解决方案1】:
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)

【讨论】:

    【解决方案2】:

    你可以这样做:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-15
      • 1970-01-01
      • 2016-05-17
      • 2015-09-11
      • 2019-08-08
      • 2011-03-17
      • 1970-01-01
      相关资源
      最近更新 更多