如何在 Python 中的数字和文本之间放置分隔符?
我在以下文本中放置分隔符时遇到问题。我想放置一个“|”文本之间以及后续 3 个数字之间。问题是有时数字实际上是破折号来表示 0(即 -- 而不是 0)。
text = """
A line of text 85 25,653 -75,321
Another - line 5,432 (5,353) --
Another one 23 -0- 86
One -- more -- -0- 34 25
"""
到目前为止,我可以得到大部分的“|”分隔符,使用以下代码:
text = re.sub(r'\s[(](\d)', '|(\\1', text)
text = re.sub(r'\s(\d)', '|\\1', text)
text = re.sub(r'\s-(\d)', '|-\\1', text)
此输出:
A line of text |85 |25,653 |-75,321
Another - line |5,432 |(5,353) --
Another one |23 |-0- |86
One -- more --|-0-|34|25
但是,我想要在第 4 行中的第二个 -- 之前有另一个分隔符,而不在 One 和 -- 之间放置分隔符。有没有办法在 Python 中做到这一点?
我希望最终的输出是:
A line of text |85 |25,653 |-75,321
Another - line |5,432 |(5,353) |--
Another one |23 |-0- |86
One -- more |--|-0-|34|25
I'm having trouble placing delimiters in the following text. I want to place a '|' between the text and between each of the 3 subsequent numbers. The problem is that sometimes the numbers are actually dashes to signify 0 (i.e., -- instead of 0).
text = """
A line of text 85 25,653 -75,321
Another - line 5,432 (5,353) --
Another one 23 -0- 86
One -- more -- -0- 34 25
"""
So far, I can get most of the '|' delimiters, using the following code:
text = re.sub(r'\s[(](\d)', '|(\\1', text)
text = re.sub(r'\s(\d)', '|\\1', text)
text = re.sub(r'\s-(\d)', '|-\\1', text)
This outputs:
A line of text |85 |25,653 |-75,321
Another - line |5,432 |(5,353) --
Another one |23 |-0- |86
One -- more --|-0-|34|25
However, I want another delimiter before the second -- in row 4 without placing a delimiter between One and --. Is there a way to do this in Python?
I would like the final output to be:
A line of text |85 |25,653 |-75,321
Another - line |5,432 |(5,353) |--
Another one |23 |-0- |86
One -- more |--|-0-|34|25
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用Python 字符串方法:
这会在有空格的地方分割行,然后使用|。
|
连接三个数据列,并使用将文本连接在一起,然后在文本和数据之间添加最终的
Using Python string methods:
This splits the line wherever there is whitespace, then joins the three data columns with
|
s and the text together withs, then adds a final
|
between the text and the data.