【问题标题】:How to separate using characters instead of whitespace in python如何在python中使用字符而不是空格来分隔
【发布时间】:2020-03-17 18:42:03
【问题描述】:

我有一个文本文件,例如:

测试用例 1 通过

测试用例 2 通过

等等等等等等

我可以使用 split() 函数通过空格分隔字符串,但我想使用关键字“Pass”/“Fail”将它们分开,我应该怎么做?

我当前的代码支持通过空格分隔,但并非所有文本文件都有相似的值,但它们会有“通过”或“失败”关键字

filestr = ''
f = open('/Users/shashankgoud/Downloads/abc/index.txt',"r")
data=f.read()
for line in data.split('\n'):
    strlist = line.split(' ')
    filestr += (' '.join(strlist[:3]) +','+','.join(strlist[3:]))
    filestr += '\n'

print(filestr)

f1 = open('/Users/shashankgoud/Downloads/abc/index.xlsx',"w")
f1.write(filestr)
f1.close()

【问题讨论】:

标签: python python-3.x substring


【解决方案1】:

您可以为此使用re 模块,例如:

import re

txt = "test case 1 Pass Test case 2 Pass etc etc etc"
pattern = re.compile(r'(Pass|Fail)')

parts = pattern.split(txt)
joined_parts = [
    parts[i] + parts[i + 1] for i in range(0, len(parts) - 1, 2)
]
joined_parts += [parts[-1]]
print(joined_parts)


>>> ['test case 1 Pass', ' Test case 2 Pass', ' etc etc etc']

【讨论】:

  • 虽然这确实帮助我使用关键字通过或失败进行分离(谢谢分享)但我仍然无法分离文本文件内容,如果有一个 \n 然后通过,失败就消失了..我希望他们在那里,以便当我将该文本文件转换为 excel 时,通过/失败列在单独的列中。抱歉成为麻烦的编码员
  • @ShashankGoud,现在分隔符不会消失。查看更新。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-27
  • 2013-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-23
相关资源
最近更新 更多