簡體   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