Ali Alshehri Ali Alshehri - 6 days ago 6
Python Question

python adding space after certain clusters or characters

I have a text file that looks like the following:


AELSLAEM A3LYKM

AELSLAEM A3LYKM WRH7MT3 AELLHH WBRKAETHH

HHL TSMH7 LY

LW SMH7T

MN FD9LK

HHL TTKRM A3LY B

MN FD9LK AHRYD

AHNAE AHRYD MN FD9LK

MN FD9LK AHH7D9R LY

HHL LDYK H7JHZ

AENTDH6R QLYLAE

SAHNTDH6R HHNAE

MTAE YGHLQ AELMT6A3M

MTAE YFTH7 AELMT6A3M ...


I would like to add a white space after each of these characters:


characters = [AH, AE2, UW, EH, AE, B, T3, T, TH, JH, H7, X, D, DH, R, Z, S, SH, S9, D9, T6, DH6, A3, GH, F, Q, K, L, M, N, HH, W, Y, AA, AN, IH, EN, UN, 2]


so the output would look like the following:


AE L S L AE M A3 L Y K M

AE L S L AE M A3 L Y K M W R H7 M T3 AE L L HH W B R K AE T HH

HH L T S M H7 L Y

L W S M H7 T

M N F D9 L K

HH L T T K R M A3 L Y B

M N F D9 L K AH R Y D


What I am mostly having trouble with is adding space, for example, after D only if it is followed by a digit or H.. I would like to do this in python or (if possible) vim. Could any one help with this. thank you!

Answer

You can try using the replace method. So you go through the character array using a for each loop (or regular for loop if you prefer) and say replace all instances of this character with the character plus a space:

for chars in characters:
{
    str = str.replace(chars, chars + ' ')
}

That's assuming you read in the file into a variable called str.

Comments