繁体   English   中英

从python上的文本文件中删除字符串开头的空格

[英]remove spaces from the beginning of string from text file on python

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

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 文件中删除这些额外的空间,我可以同时进行吗以上脚本还是我应该在单独的脚本中执行此操作? 谢谢。

将 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM