【问题标题】:remove spaces from the beginning of string from text file on python从python上的文本文件中删除字符串开头的空格
【发布时间】:2021-01-23 01:33:52
【问题描述】:

我有一个类似波纹管的列表,需要拆分为前缀/根/后缀

Input
form
jalan
ba-jalan
pem-porut#an
daun #kulu
daun#kulu
tarik-napas
tarik#napas
n-cium #bow
arau/araw
imbaw//nimbaw
dengo | nengo
dodop=am
{di} dalam
di {dalam}

我在 python 上通过下面的正则表达式完成了它:

import sys
 sys.stdout = open('final.txt', 'w')

import re
 open('split.txt') as f:
  new_split = [item.strip() for item in f.readlines()]

for word in new_split:
 m = re.match(r"(?:\{[^-#={}/|]+\})?(?:([^-#={}/|]+)-)?([^-#={}/|]+)(?:/[^-#={}/|]+)?(?:[#=]([^-#={}/|]+))?", word)
if m:
    print("\t".join([str(item) for item in m.groups()]))
else:
    print("(no match: %s)" % word)

最终的输出如下所示。

None    jalan   None
ba  jalan   None
pem porut   an
None    daun    kulu
None    daun    kulu
tarik   napas   None
None    tarik   napas
n   cium    bow
None    arau    None
None    imbaw   None
None    dengo   None
None    dodop   am
None     dalam  None
None    di  None

现在,正如您在输出文件底部的单词 dalam 中看到的,在 dalam 之前有额外的空间,而其他一些词在字符串之前也有额外的空间 如何从 final.txt 文件中删除这些额外的空间我可以做到吗在上面的脚本中还是应该在单独的脚本中这样做?谢谢。

【问题讨论】:

  • 你想要的结果是什么?

标签: python python-3.x regex removing-whitespace


【解决方案1】:

将 lstrip() 添加到字符串以删除前导空格。

str(item).lstrip()

代码:

import re
with open('split.txt') as w:
    new_split = [item.strip() for item in w.readlines()]


for word in new_split:
    m = re.match(r"(?:\{[^-#={}/|]+\})?(?:([^-#={}/|]+)-)?([^-#={}/|]+)(?:/[^-#={}/|]+)?(?:[#=]([^-#={}/|]+))?", word)
    if m:
        print("\t".join([str(item).lstrip() for item in m.groups()]))
    else:
        print("(no match: %s)" % word)

【讨论】:

    猜你喜欢
    • 2011-08-30
    • 1970-01-01
    • 1970-01-01
    • 2017-02-20
    • 2016-09-30
    • 2011-12-22
    • 2015-07-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多