【问题标题】:Replacing double space with single space in line containing certain string用包含某些字符串的行中的单个空格替换双空格
【发布时间】:2019-12-04 19:14:12
【问题描述】:

我有一个包含行和列的大文本文件。在文件中的所有字符串/数据之间,有一个双空格。但是,为了使我的特定代码正常工作,我需要双空格仅在某些行中成为单空格。这些行都以相同的字符串开头。

我试过了:

with open(outfile) as f3, open(outfile2,'w') as f4:
    for line in f3:
         line = line.strip()
         if "SAMPLE" in line:
             " ".join(line.split())
         if 'xyz' not in line and len(line) >=46:
             f4.write(line+'\n')  

我试过了:

import re
with open(outfile) as f3, open(outfile2,'w') as f4:
    for line in f3:
         if "SAMPLE" in line:
             re.sub("\s\s+" , " ", line)
         if 'xyz' not in line and len(line) >=46:
             f4.write(line)  

都不行。第二个 if 语句删除一些我不想要的行,这样就不会消失(这按预期工作)。但是,文本文件中所有数据之间的双倍间距仍然存在。如何使文件中包含“SAMPLE”的行用单个空格替换行中单词之间的双空格?

【问题讨论】:

  • 或许使用if "SAMPLE" in line: line.replace(" "," ")(双倍空格,单倍空格)。现在你被一个空格分割,所以返回的数组的元素是在有双空格的点上的空格。
  • re.sub("\s\s+" , " ", line)".join(line.split()) 返回一个新字符串,但您没有将它分配给任何变量,因此它会立即被丢弃。将line =" ".join(line.split())line = re.sub("\s\s+" , " ", line) 放在前面。
  • 这些都不起作用。第二个 if 语句似乎覆盖了它,因为它也被称为“行”。我需要第二个 if 语句。
  • 在没有第二个的情况下尝试第一个 if 语句(只是为了看看它是否有效)只会写入包含“SAMPLE”字符串的行。我需要文件中的所有数据(包括不包含该字符串的行)仍然写入输出文件。

标签: python regex split whitespace removing-whitespace


【解决方案1】:

试试这个:

s = " ".join(your_string.split())

【讨论】:

  • 但是他试过了,还是不行,因为your_string.split()返回的数组中有" "
  • @Ardweaden 注意细节,他没有做作业。根据docs,不带参数(或不带参数)调用的.split() 也会被任意数量的连续空格分割
  • 啊,我明白了。谢谢你。
  • 是的,我确实这样做了,但它不起作用,所以我没有在我的示例中包含。我试图解释。双 if 语句没有单独隔离行。
  • 如果您解释了代码如何回答问题,这将是一个更好的答案。
【解决方案2】:

您的问题是字符串的可变性," ".join(line.split()) 创建了一个新字符串,这很可能是您需要的,但您应该将其分配回 line 变量。

if "SAMPLE" in line:
    line = " ".join(line.split())

稍后编辑:
第二个if 有点“奇怪”……预期的结果是什么?

if not line or (':' and len(line) >=46):
    f4.write(line) 

尤其是第二部分...':' 总是评估为True,似乎没用可能是错字或缺少的东西。 仅当line 为空或无(计算为False)或行长为>= 46 时,才会写入文件。

代码应如下所示:

with open(outfile) as f3, open(outfile2,'w') as f4:
    for line in f3:
         line = line.strip()
         if "SAMPLE" in line:
             # we clean eventual double/multi-space if the line contains "SAMPLE"
             line = " ".join(line.split()) 
         if 'xyz' not in line and len(line) >=46:
             # write to the second file only the lines that
             # don't contain 'xyz' and have the length of the line => 46 
             f4.write(line+'\n')  

【讨论】:

  • 我也试过这个。它不会改变任何东西。它就像那行代码甚至不存在。另外,我仍然需要为第二个 if 语句考虑“行”。
  • 最简单的调试方法是添加 print 调用 "everywhere" 以了解正在发生的事情。
  • 我知道。它不工作。如果我在没有第二个 if 语句的情况下尝试它,它只会用“SAMPLE”编写包含该字符串的行。我还需要写入所有数据。
  • 第二个 if 语句只是为了去掉文件中包含“:”和那个长度的一些行。它工作正常。
  • 如果语句不检查行中的':',它应该包含':' in line。请提供输入文件的样本(如果它不包含私人数据)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-25
  • 1970-01-01
  • 2011-09-04
  • 1970-01-01
  • 1970-01-01
  • 2015-08-03
  • 2016-06-16
相关资源
最近更新 更多