[英]Manipulating stdin and redirect to stdout in Python
我正在嘗試編寫一個簡單的python腳本,其中
我只有一部分從stdin中獲取值並尋找匹配的單詞,在那之后我有點卡住了。
import re
import sys
for line in sys.stdin:
matchObj = re.search(r'<something>(.*)</something>',line)
if matchObj:
oldWord = matchObj.group(1)
print oldWord
foo的內容
<something>REPLACEME</something>
<blah>UNTOUCH</blah>
理想情況下,如果我運行此命令
cat foo | ./test.py
我會得到這樣的東西
<something>NEWWORD</something
<blah>UNTOUCH</blah>
您在尋找re.sub嗎?
import re
import sys
for line in sys.stdin:
sys.stdout.write(re.sub(r'(<something>)REPLACEME(</something>)',
r'\1NEWWORD\2',
line))
在示例數據上運行以上代碼:
$ echo '<something>REPLACEME</something>\n<something>UNTOUCH</something>' | python2 test.py
<something>NEWWORD</something>
<blah>UNTOUCH</blah>
請注意,使用正則表達式解析XML可能不是一個好主意。 Python標准庫帶有許多XML模塊 。
這是一個例子:
import sys
import xml.etree.ElementTree
tree = xml.etree.ElementTree.parse(sys.stdin)
root = tree.getroot()
for node in root.iter('something'):
if node.text == 'REPLACEME':
node.text == 'NEWWORD'
tree.write(sys.stdout)
上面的工作原理是一樣的:
$ echo '<root><something>REPLACEME</something>\n<blah>UNTOUCH</blah></root>' | python2 test.py
<root><something>REPLACEME</something>
<blah>UNTOUCH</blah></root>
如果您運行cat foo | ./test.py
則將cat foo | ./test.py
cat foo | ./test.py
您test.py: command not found
,您需要運行以下命令: cat foo |python ./test.py
。
那么您的代碼輸出將是:
REPLACEME
但是對於所需的輸出,您需要使用re.sub()
:
import re
import sys
for line in sys.stdin:
matchObj = re.sub(r'<something>(.*)</something>','<something>NEWWORD</something>',line)
if matchObj:
print matchObj
輸出:
<something>NEWWORD</something>
<blah>UNTOUCH</blah>
另外,作為Python方式,您可以使用ElementTree XML API
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.