Extract information in a line of text with a format from user input

落花浮王杯 提交于 2019-12-08 18:59:26

Well, you can use the string method split to split the string by _-_.

and for taking the input from the command line, you can use sys.argv to get that.

here's an example:

import sys
number,title = sys.argv[1].split("_-_")

Update:

Surely you can pass the pattern as a first argument and the file as the second argument like that:

import sys
pattern = sys.argv[1]
number,title = sys.argv[2].split(pattern)

Now if you need more complex and dynamic processing, then Regex is your winning card!

And in order to write a good regex, you got to understand your data and your problem or you'll end up writing a glitchy regex

You can elaborate on this. It is a very simple example, though.

import re
p = re.compile('([0-1][0-1])_\-_(.*)\.mp3')
title = '01_-_Respect.mp3'
p.findall(title)

Output [('01', 'Respect')]

I use this page to play with regex.

Update

Since the format is given, go with string slicing. Ok, pretty limited to the specific case..

number = title[:title.find('_')]
>>> number
'01'
>>> track = title[len(number) + 3:len(title)-4]
>>> track
'Respect'

Try This code:

(considering argument is given in runtime)

tmp=$1
num=echo ${tmp%%_*}
title=echo ${tmp##*_}|cut -d. -f1

Variables num and title will store the parts from the argument

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!