How to extract certain strings start with a symbol from a text file in python?

江枫思渺然 提交于 2019-12-11 08:20:09

问题


How can i extract all words start from symbol '$' from a text file?

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

回答1:


Use 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']

Now use str.join to get the expected output:

>>> print "\n".join(ans)
$severity
$description
$eventID
$eventURL
$alertLevel
$eventStart
$eventSourceCount
$eventSourceTable
$eventDestCount



回答2:


Use regular expressions, noticing the escaping of $ (usually line-end) with \. Read the entire file at once with f.read() (Which can also be extracted to another line for enhanced readability)

import re

with open("filename", "r") as f:
...     matches = re.findall("(\$\w+)", f.read())
print matches


来源:https://stackoverflow.com/questions/18267978/how-to-extract-certain-strings-start-with-a-symbol-from-a-text-file-in-python

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