【发布时间】: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