gpt4 book ai didi

python - 如何从Python文本文件中提取以符号开头的某些字符串?

转载 作者:行者123 更新时间:2023-12-01 05:38:32 24 4
gpt4 key购买 nike

如何从文本文件中提取以符号“$”开头的所有单词?

文件 (ascii) -->

        @ExtendedAttr = nvp_add(@ExtendedAttr, "severity", $severity,  
"description", $description, "eventID", $eventID,
"eventURL", $eventURL, "alertLevel", $alertLevel,
"eventStart", $eventStart,
"eventSourceCount", $eventSourceCount, "eventSourceTable",
$eventSourceTable, "eventDestCount", $eventDestCount)

我希望输出像这样(全部换行):

$severity
$description
$eventID
$eventURL
$alertLevel
$eventStart
$eventSourceCount
$eventSourceTable
$eventDestCount

最佳答案

使用正则表达式:

>>> 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 获得预期的输出:

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

关于python - 如何从Python文本文件中提取以符号开头的某些字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18267978/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com