【问题标题】:Line split when multiple white spaces in pythonpython中多个空格时的行拆分
【发布时间】:2020-07-23 06:08:27
【问题描述】:

我查看了许多类似的问题,但是我的分隔符不是特殊字符,例如“\”或“*”,因此没有一个解决方案有效。 我正在将结果写入 python 中的文件,然后重新打开它以读取和处理。

file1.txt
control1
1  10      12
1  34      44
2   1      -3
control2
3   4     -10.3
3   3.390   4

我将每个条目分开,直到我看到 chapters 中有“控制”的行:

import re
import sys, string, glob, os
with open('file1.txt') as f:
        with open("control_output.txt", "w") as output:
            mytext = f.read()
            chapter = re.split("control[0-2]+\n", mytext)
            i=1
            print chapter[i]
            output.write(chapter[i])
            for filename in glob.glob(os.path.join(filePath, 'control_output.txt')):
                 merged_table=open(filename,'r')
                 for line in merged_table:
                      line = line.strip().split('\t')
                      print line

但是它什么也不打印,因为该行没有制表符分隔符。 如果我在读取文件之前退出脚本,并将所有空格更改为制表符,那么它可以工作:

sed -i 's/ \+ /\t/g' control_output.txt 

然后我有输出:

['1', '10', '12']
['1', '34', '44']
['2', '1', '-3']

我也尝试过 subprocess.call

subprocess.call(["sed", "-i",  's/ \+ /\t/g', "control_output.txt"])

然后我有输出:

[[]]

我尝试使用多个空格进行 re.split:

line = re.split(r'\s*', line)

这也给了

[[]]

但是预期的输出应该是:

['1', '10', '12']
['1', '34', '44']
['2', '1', '-3']

如何用多个分隔符分割字符串?

【问题讨论】:

  • 在 Python 中使用正则表达式分割多个空格是使用 line = re.split(r'\s+', line) 完成的。 \s* 将在任何不匹配的符号之前匹配。
  • 你试过简单的line.strip().split()吗?
  • 请将该示例输入的所需输出(无描述)添加到您的问题(无评论)。
  • 我添加了预期的输出。我尝试了你的两个解决方案..我有一个空列表作为这些的输出

标签: python sed split tabs space


【解决方案1】:
for line in merged_table:
    line = line.strip().split()
        print line

这将拆分所有空格,而不仅仅是制表符

【讨论】:

  • 感谢您的回复,但是使用此解决方案我仍然有空输出:[[]]
【解决方案2】:
import re
import sys, string, glob, os
with open('file1.txt') as f:
    with open("control_output.txt", "w") as output:
        mytext = f.read()
        chapter = re.split("control[0-2]+\n", mytext)
        i=1
        print chapter[i]
        output.write(chapter[i])

    # You should move this code block out of with open("control_output.txt", "w") as output:
    for filename in glob.glob(os.path.join(filePath, 'control_output.txt')):
        with open(filename, 'r') as f_table:
            merged_table = f_table.readlines()

        for line in merged_table:
            line = re.split('\s+', line.strip())
            print line

希望能帮到你?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-15
    • 1970-01-01
    • 1970-01-01
    • 2021-01-23
    相关资源
    最近更新 更多