get line of a predefined sentence that in a txt file line?
so i have this code:
for line in open('music.txt'):
if '开发者_如何学运维file : "' in line:
c = line.split('file : "')
del c[0]
d="".join(c)
a=re.sub('"','',d)
e=re.sub(',','',a)
urls.append(e)
Is there a way to do this but without a file?
Maybe you want something like that:
urls = [re.findall(r'file : "(.*)"', line)[0].replace(',', '')
for line in file if 'file :' in line]
and it works on any file object or list.
For standard input, use file = sys.stdin
Example:
file = ['file : "test, 123, 456, abcde"',
'other line',
'file : "zzzzzzzzz"]
output:
['test 123 456 abcde', 'zzzzzzzzz']
If you want to read from standard input (for example, in a pipeline) then you can just write
import sys
for line in sys.stdin:
And the rest will work. (sys.stdin
is an open file corresponding to standard input)
If you have the lines in a list, then you can just iterate across the list using the same code.
精彩评论