如何从python中的文本文件中提取以符号开头的某些字符串? [英] How to extract certain strings start with a symbol from a text file in python?
本文介绍了如何从python中的文本文件中提取以符号开头的某些字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何从文本文件中提取所有从符号"$"开始的单词?
How can i extract all words start from symbol '$' from a text file?
提交一个(ascii)->
File a (ascii) -->
@ExtendedAttr = nvp_add(@ExtendedAttr, "severity", $severity,
"description", $description, "eventID", $eventID,
"eventURL", $eventURL, "alertLevel", $alertLevel,
"eventStart", $eventStart,
"eventSourceCount", $eventSourceCount, "eventSourceTable",
$eventSourceTable, "eventDestCount", $eventDestCount)
我希望输出像这样(都在新行中):
I want the output to be like this (all in new line) :
$severity
$description
$eventID
$eventURL
$alertLevel
$eventStart
$eventSourceCount
$eventSourceTable
$eventDestCount
推荐答案
使用regex
:
>>> import re
>>> with open('filename') as f:
... ans = []
... for line in f:
... matches = re.findall(r'(?<!\w)(\$\w+)', line)
... ans.extend(matches)
...
>>> print ans
['$severity', '$description', '$eventID', '$eventURL', '$alertLevel', '$eventStart', '$eventSourceCount', '$eventSourceTable', '$eventDestCount']
现在使用str.join
获得预期的输出:
Now use str.join
to get the expected output:
>>> print "\n".join(ans)
$severity
$description
$eventID
$eventURL
$alertLevel
$eventStart
$eventSourceCount
$eventSourceTable
$eventDestCount
这篇关于如何从python中的文本文件中提取以符号开头的某些字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文