![](/img/trans.png)
[英]How to search for the word in each line of a file and print the next value of it in python
[英]Search and replace a word within a line, and print the result in next line
我有一個腳本,其中包含多行此行:
Wait(0.000005);
目的是使搜索/替換功能轉換為以下格式:
//Wait(0.000005);
Wait(5);
注釋掉“等待(0.000005)”的第一部分; 已經完成了。 無法從第一行進行替換。
有人可以啟發我。 謝謝。
這是使用sed在命令行中進行替換的一種方法:
sed 's/Wait(0.000005);/ \/\/Wait(0.000005);\'$'\nWait(50);/' filename.py
import re
regex = re.compile(r"^.*Wait(0.000005);.*$", re.IGNORECASE)
for line in some_file:
line = regex.sub("^.*Wait(0.000005);.*$","Wait(50);", line)
這可能是一種解決方案
正則表達式在這里非常方便:
import re
with open("example.txt") as infile:
data = infile.readlines()
pattern = re.compile("Wait\(([0-9]+\.[0-9]*)\)")
for line in data:
matches = pattern.match(line)
if matches:
value = float(matches.group(1))
newLine = "//" + matches.group(0) + "\n\n"
newLine += "Wait(%i)" % (value * 10000000)
print newLine
else:
print line
輸入示例:
Wait(0.000005);
Wait(0.000010);
Wait(0.000005);
輸出示例:
//Wait(0.000005)
Wait(50)
//Wait(0.000010)
Wait(100)
//Wait(0.000005)
Wait(50)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.