我有一个用Python编写的程序,可以打印代码:
<script type="text/javascript" language="JavaScript">
ArtistName = "FUN.";
SongName = "We Are Young";
</script>
我曾尝试在awk中编写一个脚本,允许我将ArtistName和SongName保存为变量但无法看清楚。有没有办法在python中执行此操作?
答案 0 :(得分:0)
如果需要,可以使用正则表达式将ArtistName
和SongName
保存为字典中的键。
以下是正则表达式解释的一些链接:Python Docs和Tutorials Point
import re
s = #string you're parsing
regex = re.compile(r'\w+ = \".*\";')
matches = regex.findall(s)
dict1 = {}
for m in matches:
elems = m.split(" = ")
dict1[str(elems[0])] = elems[len(elems) - 1].strip(';')
print (dict1['ArtistName'])
print (dict1['SongName'])
输出(使用您的示例字符串):
'"FUN."'
'"We Are Young"'
答案 1 :(得分:0)
如果您的数据足够一致,您可以使用正则表达式逃脱(只要您没有"
等名称...),例如:
text="""<script type="text/javascript" language="JavaScript">
ArtistName = "FUN.";
SongName = "We Are Young";
</script> """
import re
print dict(re.findall(r'((?:Artist|Song)Name)\s=\s"([^"]*)"', text))
# {'ArtistName': 'FUN.', 'SongName': 'We Are Young'}