简体   繁体   中英

Can I make a list comprehension of this python code?

for i in os.listdir('./Python'):
    f=open(os.path.join('./Python',i)).read().split()
    g=[re.sub('[<TEI[.+]<body>]','',j)
    for j in f if re.sub('[<TEI[.+]<body>]','',j)]:
       open(os.path.join('./Python/',i),'w').write('\n'.join(g))

Can I make a list comprehension of this code?. Fixed the for loop.

Not sure if this will work but it provides the concept.

opn = lambda i : open(os.path.join('./Python',i)).read().split()
lst = lambda i : [re.sub('[<TEI[.+]]','',j) for j in opn(i) if re.sub('[<TEI[.+]]','',j)] 
wrt = lambda i,g : open(os.path.join('./Python/',i),'w').write('\n'.join(lst(i)))
[(i,wrt(i)) for i in os.listdir('./Python')]

Here is single line

[(i,open(os.path.join('./Python/',i),'w').write('\\n'.join([re.sub('[<TEI[.+]]','',j) for j in open(os.path.join('./Python',i)).read().split() if re.sub('[<TEI[.+]]','',j)] )) for i in os.listdir('./Python')]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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